循环到对象数组和对属性的访问

Loop into an array of objects and access to properties

本文关键字:属性 访问 对象 数组 循环      更新时间:2023-09-26

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

 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 中对象的每个实例的列表,但它仅从中检索第一个对象。那么,如何正确访问这些值呢?谢谢

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