-2

如果我有这个:

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

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

请不要查询

4

5 回答 5

1

您可以像这样使用地图:

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

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

于 2016-11-14T13:07:45.500 回答
1

尝试这个

for (var i=0;i<myArr.length; i++){
    if (myArr[i].name!=undefined){
      mySecondArr.push(myArr[i].name)
}
于 2016-11-14T13:06:19.123 回答
0

您可以使用该map函数并返回secondName

var result = myArr.map(function(a) {return a.secondName;});
于 2016-11-14T13:07:28.050 回答
0

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

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

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

console.log(mySecondArr);

于 2016-11-14T13:08:24.230 回答
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);
于 2016-11-14T13:09:14.773 回答