循环到对象数组并访问属性

时间:2016-02-29 17:23:47

标签: javascript arrays for-loop

我检查了其他问题来解决这个问题,但我无法弄清楚如何在我的情况下解决它:我想循环遍历对象数组的所有项目并访问特定属性。

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

我的数据阵列结构:

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

检查控制台输出是myArray中对象的每个实例的列表,但它只从中检索第一个对象。那么,我如何正确访问这些值?感谢

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
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);
&#13;
&#13;
&#13;