jQuery: Looping through object properly?

前端 未结 2 1256
悲哀的现实
悲哀的现实 2021-02-12 16:43

I am trying to loop through the below shown JS object with the following code snippet, while needing to fetch both the index key as well as the inner object.

How on ear

2条回答
  •  灰色年华
    2021-02-12 17:06

    The inner object you're fetching fine, valueObj is the array, it just has no method .toSource() (at least not cross-browser anyway), if you remove that you'll get an alert:

    $.each(myObject, function(key,valueObj){
        alert(key + "/" + valueObj );
    });
    

    You can test it out here, don't be thrown that the output is just:

    prop_1/1,2
    prop_2/3,4
    

    ...the default .toString() on an Array is a comma delimited list, so that's what you see with an alert(). For example, if you instead did alert(key + "/" + valueObj[0] );, you'd see:

    prop_1/1
    prop_2/3
    

    ...so you can see you do have the Array you want, you can test that here.

提交回复
热议问题