最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert array of objects into array by field with Underscore.js or jQuery - JavaScript - Stack Overflow

programmeradmin3浏览0评论

Is there a way to convert an array like this:

"team" : [   {       "player" : "John",   "rank" : 0 }, {       "player" : "Peter",   "rank" : 2 } ]

to this:

"team" : [ "John", "Peter" ]

with Underscore.js or jQuery?

Any help would be greatly appreciated.

Is there a way to convert an array like this:

"team" : [   {       "player" : "John",   "rank" : 0 }, {       "player" : "Peter",   "rank" : 2 } ]

to this:

"team" : [ "John", "Peter" ]

with Underscore.js or jQuery?

Any help would be greatly appreciated.

Share Improve this question asked Nov 5, 2014 at 19:23 user3475602user3475602 1,2172 gold badges22 silver badges43 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Use pluck:

A convenient version of what is perhaps the most mon use-case for map: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

You could do it with plain old javascript via the map function

var someArray = [
    {name:'John', age:23},
    {name:'Foo', age:34},
    {name:'Bar', age:10},
    {name:'Doe', age:65}
];
var nameArray = someArray.map(function(el) {return el.name;});

With pure JavaScript Just iterate through it and push the player into a new array:

var array = [];
for(i in team){
  array.push(team[i].player);
}

or with underscore.js use plug

var array = _.pluck(team, 'player');
发布评论

评论列表(0)

  1. 暂无评论