我目前有一个对象数组,每个对象都有几个属性。例子:
[
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
]
将其转换为包含text
值的字符串数组的最佳方法是什么?我本以为我可以使用underscore.js:
headerText = _.pick(headerRow, 'text');
但我认为,因为对象是在一个数组中,这将不工作。我的下一个想法是只是循环通过数组中的每个元素,并推动text
值到一个新的数组,但我很好奇,如果有人知道一个更优雅的方式来做到这一点?建议吗?
你要找的是Array#map
:
var stringArray = headerRow.map(function(entry) {
return entry.text;
});
实例|来源
你甚至不需要下划线,Array#map
是ES5的一部分,完全支持V8, Node使用的JavaScript引擎。对于数组中的每个条目,Array#map
调用您给它的函数一次,并根据该函数的返回值构建一个新数组。
或者如果你想改变现有的数组,你可以使用Array#forEach
:
headerRow.forEach(function(entry, index) {
headerRow[index] = entry.text;
});
实例|来源
使用_.map(headerRow, function(row) { return row.text; })
。Array.map
在IE <中不可用;9 .
我将使用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);
这是一个普通的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"]