Javascript 根据属性将对象数组分解为单独的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14696326/
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
break array of objects into separate arrays based on a property
提问by Evan
Say I have an array like this:
假设我有一个这样的数组:
var arr = [
{type:"orange", title:"First"},
{type:"orange", title:"Second"},
{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}
];
and I want this to be split up into arrays that have objects which have same type so:
我希望将其拆分为具有相同类型对象的数组,因此:
[{type:"orange", title:"First"},
{type:"orange", title:"Second"}]
[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]
But I want to do this generically so not having an if statement that specifies orange or banana
但我想一般地这样做,所以没有指定橙色或香蕉的 if 语句
// not like this
for (prop in arr){
if (arr[prop] === "banana"){
//add to new array
}
}
Thoughts? JQuery and Underscore are both options to use.
想法?JQuery 和 Underscore 都是可以使用的选项。
采纳答案by Bergi
JQuery and Underscore are both options to use.
JQuery 和 Underscore 都是可以使用的选项。
Underscore's groupBydoes exactly what you need.
Underscore 的groupBy功能正是您所需要的。
_.groupBy(arr, "type")
回答by maerics
This is an easy job for Array.reduce(...):
这是一项轻松的工作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"}]
Of course, if your target browser(s) do not support ECMAScript 262 5th edition then you'll have to implement "reduce" by yourself, or use a polyfill library, or choose another answer.
当然,如果您的目标浏览器不支持 ECMAScript 262 第 5 版,那么您必须自己实现“reduce”,或者使用 polyfill 库,或者选择其他答案。
[Update]Here's a solution that should work with any version of JavaScript:
[更新]这是一个适用于任何版本的 JavaScript 的解决方案:
function groupBy2(xs, prop) {
var grouped = {};
for (var i=0; i<xs.length; i++) {
var p = xs[i][prop];
if (!grouped[p]) { grouped[p] = []; }
grouped[p].push(xs[i]);
}
return grouped;
}
回答by Shmiddty
This assumes an array of objects:
这假设一个对象数组:
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]}
回答by Travis J
Just build a dictionary which holds the objects based on their title. You could do it like this:
只需构建一个字典,根据标题保存对象。你可以这样做:
js
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/
jsfiddle 演示:http: //jsfiddle.net/YJnM6/
回答by denolsson
Typescript version.
打字稿版本。
/**
* Group object array by property
* Example, groupBy(array, ( x: Props ) => x.id );
* @param array
* @param property
*/
export const groupBy = <T>(array: Array<T>, property: (x: T) => string): { [key: string]: Array<T> } =>
array.reduce((memo: { [key: string]: Array<T> }, x: T) => {
if (!memo[property(x)]) {
memo[property(x)] = [];
}
memo[property(x)].push(x);
return memo;
}, {});
export default groupBy;
回答by Watchmaker
ES6 solution:
ES6解决方案:
function groupBy(arr, property) {
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
or completely ES6fy:
或完全 ES6fy:
const groupBy = (arr, property) => {
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
I hope it helps!
我希望它有帮助!

