0

我目前有一个对象数组,其中每个对象都有几个属性。例子:

[
   { text: 'test1',
     id: 1
   },
   { text: 'test2',
     id: 2
   }
]

将其转换为包含 from 值的字符串数组的最佳方法是text什么?我原以为我可以使用underscore.js做到这一点:

headerText = _.pick(headerRow, 'text');

但我认为,由于对象位于数组中,这将不起作用。我的下一个想法是循环遍历数组中的每个元素并将text值推送到一个新数组,但我很好奇是否有人知道更优雅的方法来做到这一点?建议?

4

4 回答 4

4

您正在寻找Array#map

var stringArray = headerRow.map(function(entry) {
    return entry.text;
});

实例| 来源

你甚至不需要 Underscore,Array#map它是 ES5 的一部分,并且完全支持 V8,Node 使用的 JavaScript 引擎。Array#map为数组中的每个条目调用一次您给它的函数,并根据该函数的返回值构建一个新数组。

或者,如果要更改现有数组,可以使用Array#forEach

headerRow.forEach(function(entry, index) {
    headerRow[index] = entry.text;
});

实例| 来源

于 2013-03-04T16:45:22.517 回答
1

使用_.map(headerRow, function(row) { return row.text; }). Array.map在 IE < 9 中不可用。

于 2013-03-04T16:45:03.820 回答
0

我会使用 foreach 并循环遍历它。

 var jamie = [
    { text: 'test1',
      id: 1
    },
    { text: 'test2',
      id: 2
    }
 ];

 var length = jamie.length,
     element = [];
 for (var i = 0; i < length; i++) {
   element[i] = jamie[i].id;
   // Do something with element i.
 }
   console.info(element);
于 2013-03-04T16:46:46.913 回答
-1

这是一个香草 javascript 版本,它避免使用不普遍支持的Array.map方法。

// assign the array to a variable
var a = [
   { text: 'test1',
     id: 1
   },
   { text: 'test2',
     id: 2
   }
];

// loop through each item in the array, reassigning with it's text value
// not like this: for(i in a) a[i] = a[i].text
// but with a for loop based on the array length
var i;
for(i=a.length; i; i--){ a[i-1] = a[i-1].text; }

// check the results
console.log(a);
// ["test1", "test2"]
于 2013-03-04T16:46:46.580 回答