[英]flatten object to array in javascript
I want to transform an object like this: 我想像这样变换一个对象:
[
{ name: 'john', surname: 'doe' },
{ name: 'jane', surname: 'dee' },
]
Into an array, like this. 变成一个数组,像这样。 By choosing an arbitrary key (eg: 'name')
通过选择任意键(例如:“名称”)
[ 'john', 'jane' ]
What is the fastest way to achieve this? 最快的方法是什么? Thanks in advance.
提前致谢。
If you don't need retro compatibility (and I think you're not going to need it, since you're on NodeJS), you can simply use: 如果您不需要逆向兼容性(由于您使用的是NodeJS,我认为您将不需要它),则可以简单地使用:
var obj = [
{ name: 'john', surname: 'doe' },
{ name: 'jane', surname: 'dee' },
],
names = obj.map(function(item) {return item.name;});
Or, the "slowest" way: 或者,“最慢”的方式:
var names = []; //obj defined before
for(var i = 0; i < obj.length; i++)
names.push(obj[i].name);
If you are using UnderscoreJS , you can simply write: 如果您使用的是UnderscoreJS ,则可以简单地编写:
names = _.pluck(obj, 'name');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.