Javascript LoDash:从一组对象属性中获取一组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28354725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LoDash: Get an array of values from an array of object properties
提问by YarGnawh
I'm sure it's somewhere inside the LoDash docs, but I can't seem to find the right combination.
我确定它在 LoDash 文档中的某个地方,但我似乎找不到正确的组合。
var users = [{
id: 12,
name: Adam
},{
id: 14,
name: Bob
},{
id: 16,
name: Charlie
},{
id: 18,
name: David
}
]
// how do I get [12, 14, 16, 18]
var userIds = _.map(users, _.pick('id'));
回答by dfsq
Since version v4.x you should use _.map:
从 v4.x 版开始,您应该使用_.map:
_.map(users, 'id'); // [12, 14, 16, 18]
this way it is corresponds to native Array.prototype.mapmethod where you would write (ES2015 syntax):
这样它对应于您将在其中编写的本机Array.prototype.map方法(ES2015 语法):
users.map(user => user.id); // [12, 14, 16, 18]
Before v4.x you could use _.pluckthe same way:
在 v4.x 之前,您可以使用_.pluck相同的方式:
_.pluck(users, 'id'); // [12, 14, 16, 18]
回答by c-smile
With pure JS:
使用纯 JS:
var userIds = users.map( function(obj) { return obj.id; } );
回答by iarroyo
In the new lodash release v4.0.0_.pluckhas removed in favor of _.map
在新的lodash 版本 v4.0.0_.pluck中删除了_.map
Then you can use this:
然后你可以使用这个:
_.map(users, 'id'); // [12, 14, 16, 18]
You can see in Github Changelog
你可以在Github Changelog 中看到
回答by Andrey
And if you need to extract several properties from each object, then
如果您需要从每个对象中提取多个属性,那么
let newArr = _.map(arr, o => _.pick(o, ['name', 'surname', 'rate']));
回答by GYTO
Simple and even faster way to get it via ES6
通过 ES6 获取它的简单且更快的方法
let newArray = users.flatMap(i => i.ID) // -> [ 12, 13, 14, 15 ]
回答by Pankaj Bisht
If you are using native javascript then you can use this code -
如果您使用的是本机 javascript,那么您可以使用此代码 -
let ids = users.map(function(obj, index) {
return obj.id;
})
console.log(ids); //[12, 14, 16, 18]
回答by user1789573
This will give you what you want in a pop-up.
这将在弹出窗口中为您提供所需的内容。
for(var i = 0; i < users.Count; i++){
alert(users[i].id);
}

