-3

I checked other questions to solve this but I can not figure it out how to solve it in my case: I want to loop through all the items of an array of objects and access to an specific property.

 for (var i = 0; i < myArray.length; i++){
     var x = myArray[i].property;
     console.log(x);
 }

My data array structure:

var myArray = [ 
    firstObject: {
        title:"first",
        content:"lorem ipsum"
    },
    secondObject: {
        title:"second",
        content:"lorem ipsum"
    },
    thirdObject: {
        title:"third",
        content:"lorem ipsum"
    }
]

Inspecting the console output to be a list of each instance of the object in myArray, but it only retrieves the first object from it. So, how can I access properly to these values? Thanks

ohmmho
  • 132
  • 2
  • 13

1 Answers1

0

var myArray =
[
    {
        title: "first",
        content: "lorem ipsum"
    },
    {
        title: "second",
        content: "lorem ipsum"
    },
    {
        title: "third",
        content: "lorem ipsum"
    }
];
var arrExpectedData = [];
myArray.forEach(function (objSingle) {
    arrExpectedData.push(objSingle.title);
});
console.log(arrExpectedData);
AsgarAli
  • 2,201
  • 1
  • 20
  • 32
  • hey, yes! this works :D thank you very much! I mark it as correct. however, can you explain me the difference between the for and the forEach in this particular case? how it would be if we had on level more? I mean, imagine that the title structure instead an string is another object, like this: `title:{ date: "2016", category:"production" }` Thanks! – ohmmho Feb 29 '16 at 18:46