基于属性将对象数组分成单独的数组

假设我有一个这样的数组:

var arr = [ {type:"orange", title:"First"}, {type:"orange", title:"Second"}, {type:"banana", title:"Third"}, {type:"banana", title:"Fourth"} ]; 

我希望将它拆分为具有相同类型的对象的数组:

 [{type:"orange", title:"First"}, {type:"orange", title:"Second"}] [{type:"banana", title:"Third"}, {type:"banana", title:"Fourth"}] 

但我想一般这样做,所以没有if语句指定橙色或香蕉

 // not like this for (prop in arr){ if (arr[prop] === "banana"){ //add to new array } } 

思考? JQuery和Underscore都是可以使用的选项。

JQuery和Underscore都是可以使用的选项。

groupBygroupBy完全符合您的需求。

 _.groupBy(arr, "type") 

对于Array.reduce(...)这是一项简单的工作:

 function groupBy(arr, property) { return arr.reduce(function(memo, x) { if (!memo[x[property]]) { memo[x[property]] = []; } memo[x[property]].push(x); return memo; }, {}); } var o = groupBy(arr, 'type'); // => {orange:[...], banana:[...]} o.orange; // => [{"type":"orange","title":"First"},{"type":"orange","title":"Second"}] o.banana; // => [{"type":"banana","title":"Third"},{"type":"banana","title":"Fourth"}] 

当然,如果你的目标浏览器不支持ECMAScript 262第5版,那么你必须自己实现“减少”,或者使用polyfill库,或者选择其他答案。

[更新]这是一个适用于任何版本的JavaScript的解决方案:

 function groupBy2(xs, prop) { var grouped = {}; for (var i=0; i 

只需构建一个字典,根据标题保存对象。 你可以这样做:

JS

 var arr = [ {type:"orange", title:"First"}, {type:"orange", title:"Second"}, {type:"banana", title:"Third"}, {type:"banana", title:"Fourth"} ]; var sorted = {}; for( var i = 0, max = arr.length; i < max ; i++ ){ if( sorted[arr[i].type] == undefined ){ sorted[arr[i].type] = []; } sorted[arr[i].type].push(arr[i]); } console.log(sorted["orange"]); console.log(sorted["banana"]); 

jsfiddle demo: http : //jsfiddle.net/YJnM6/

这假设一个对象数组:

 function groupBy(array, property) { var hash = {}; for (var i = 0; i < array.length; i++) { if (!hash[array[i][property]]) hash[array[i][property]] = []; hash[array[i][property]].push(array[i]); } return hash; } groupBy(arr,'type') // Object {orange: Array[2], banana: Array[2]} groupBy(arr,'title') // Object {First: Array[1], Second: Array[1], Third: Array[1], Fourth: Array[1]}