I'm looping trough 2-dimensional objects inside an array. I currently do this the following way:
My array looks like this
var myarray = [
0: {
child_obj: {}
}
1: {//etc}
];
And I loop through the second-level objects like this
jQuery.each(myarray, function(i, first) {
jQuery.each(first.child_obj, function(j, second) {
//do stuff
}
});
});
So that's a loop inside a loop. It works fine, but it doesn't look very neat and I feel there might be a better (and shorter) way to do this. The reason I'm doing this is because I need to do stuff with all child_obj
s.
Worth mentioning:
jQuery.each()
because this allows looping through objects, while for()
, .map()
etc. can't handle that properly. i
and j
). Is there a better way?
If you want to ditch jquery (and it's slow speed in .each) and use ES2015+
var myarray = [ { child_obj: {a:1,b:2,c:3} }, { child_obj: {a:4,b:5,c:6}, child_obj2: {a:7,b:8,c:9} } ]; // specific rewrite of your code would be myarray.forEach(obj => Object.values(obj.child_obj).forEach(value => { console.log(value); })); console.log('-------'); // other examples myarray.forEach(obj => Object.values(obj).forEach(value => { // do things with each "child object" console.log(value); })); myarray.forEach(obj => Object.values(obj).forEach(child => Object.values(child).forEach(value => { // do things with each property in each child object console.log(value); })));
It's not a better way, it's more like alternate.
for (var i = 0; i < myarray.length; i++)
{
var child_obj = myarray[i].child_obj;
// get the keys of this object
var keys = Object.keys(child_obj);
// loop all those keys
for (var keyi = 0; keyi < keys.length; keyi++)
{
var key = keys[keyi];
// get the objects item based on key;
var item = child_obj[key];
}
}
but here you can change their values directly as you are iterating the original vars.
hope that helps
using underscore-js library, you can do the following:
var first = _.map(myarray, element => { return element.child_obj; });
_.each(first, element => {/*do stuff*/});
You could use forEach with a for in loop inside::
myArray.forEach(function(obj){
for(var i in obj){
// do stuff
}
})
Naive recursive approach can be used for primitive types:
function forEachPrimitive(o, f, k) { if (o !== Object(o)) f(k, o) else for (k in o) forEachPrimitive(o[k], f, k) } var obj = [ { x: { a: '0', b: true, c: 2 } }, { y: { d: /3/, e: null, f: undefined } } ] forEachPrimitive(obj, console.log)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.