-1

I've been trying to figure this out for a while and I just can't. I have an object, which has an array in it, which has objects in it. I'm trying to figure out how to use a for loop to search through the array's objects. Heres my attempt:

var obj = {
    array: [
        {"meme" : "123", "mememe" : "456"},
        {"meme" : "234", "mememe" : "567"}
    ]
}

console.log(obj.array)
for(var i in obj) {
    console.log(i);
};

This code logs the array like this:

[ { meme: '123', mememe: '456' },
  { meme: '234', mememe: '567' } ]

Then it just logs:

0
1

What I want it to log is something like

{ meme: '123', mememe: '456' }
{ meme: '234', mememe: '567' }

So I can then do something with this code.

Lucas A.
  • 99
  • 2
  • 7
  • Possible duplicate of [For-each over an array in JavaScript?](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – Blaskovicz Aug 13 '17 at 19:57

3 Answers3

0

You could iterate the array with a for statement and use the index for accessing the objects.

Mabye you have a look here, too: Why is using for ....in with array iteration a bad idea?

var obj = {
        array: [
            { meme: "123", mememe: "456"},
            { meme: "234", mememe: "567"}
        ]
    },
    i

for (i = 0; i < obj.array.length; i++) {
    console.log(obj.array[i]);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

If you only want to loop through the obj.array you can use:

for (var i = 0; i < obj.array.length; i++) {
    console.log(obj.array[1]);
}

or

for (var object of obj.array) {
    console.log(object);
}

or

obj.array.forEach(function(object) { console.log(object) });

if you want iterate over every array that might be in obj you can do this:

for (var property in obj) {
    // gets all the propertie-names of object (in this case just 'array')
    for(var object of obj[property]) {
        // iterates through all the items in the array (in this case just obj['array'])
        console.log(object);
    }
}
resumodnar
  • 26
  • 6
0

Here's one solution.

var obj = {
    array: [
        {"meme" : "123", "mememe" : "456"},
        {"meme" : "234", "mememe" : "567"}
    ]
}

obj.array.forEach(function(item) {
    console.log(item);
})

And the JSFiddle link (just turn on the dev tools (ctrl+shift+i on windows) https://jsfiddle.net/4cn6s3tf/

Bergur
  • 3,962
  • 12
  • 20