遍历对象数组并打印出 属性 值

Iterate through array of objects and print out property value

如果我有这个:

  myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

  mySecondArr = [];

我怎样才能遍历它以便 mySecondArr = ['rich', 'brian']

我正在考虑做类似的事情:

for (var key in myArr){
    if (Object.hasOwnProperty(name){
      mySecondArr.push(name[value])
}

我知道那是伪代码,但不能完全理解尽可能简单地执行此操作的语法

否JQUERY请

试试这个

for (var i=0;i<myArr.length; i++){
    if (myArr[i].name!=undefined){
      mySecondArr.push(myArr[i].name)
}

您可以使用 map 函数和 return secondName

var result = myArr.map(function(a) {return a.secondName;});

您可以像这样使用地图:

var myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

var mySecondArr = myArr.map(x => x.name);
console.log(mySecondArr);

你可以使用一个简单的map(ES6代码):

var myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

var mySecondArr = myArr.map(o => o.name);

console.log(mySecondArr);

尝试以下操作:

 var myArr = [{ name: 'rich', secondName: 'james' }, { name: 'brian', secondName: 'chris' }];

        var mySecondArr = [];

        myArr.forEach(function (data, index, myArr) {
            debugger;
            mySecondArr.push(data.name);
        });

        alert(mySecondArr);