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

时间:2016-11-14 13:03:53

标签: javascript arrays loops hasownproperty

如果我有这个:

  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])
}

我知道这是伪代码,但很难做到尽可能简单的语法

NO JQUERY PLEASE

5 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:1)

您可以像这样使用地图:

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

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

答案 2 :(得分:0)

您可以使用map功能并返回secondName

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

答案 3 :(得分:0)

您可以使用简单的map(ES6代码):

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

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

console.log(mySecondArr);

答案 4 :(得分:0)

请尝试以下操作:

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