paddotk
paddotk

Reputation: 1440

Looping through objects in array

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_objs.

Worth mentioning:

Is there a better way?

Upvotes: 0

Views: 78

Answers (5)

Slai
Slai

Reputation: 22876

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)

Upvotes: 0

user7951676
user7951676

Reputation: 367

You could use forEach with a for in loop inside::

myArray.forEach(function(obj){
for(var i in obj){
// do stuff
}
})

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

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);
})));

Upvotes: 1

OmG
OmG

Reputation: 18838

using underscore-js library, you can do the following:

var first = _.map(myarray, element => { return element.child_obj; });
_.each(first, element => {/*do stuff*/});

Upvotes: 0

masterpreenz
masterpreenz

Reputation: 2290

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

Upvotes: 0

Related Questions