如何转换这个:
[
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'},
]
Run Code Online (Sandbox Code Playgroud)
进入这个:
[
{type: 'fruit', foods: ['apple', 'banana']},
{type: 'vegetable', foods: ['potato']}
]
Run Code Online (Sandbox Code Playgroud)
使用javascript或下划线
Anu*_*rag 88
假设原始列表包含在名为的变量中list
:
_
.chain(list)
.groupBy('type')
.map(function(value, key) {
return {
type: key,
foods: _.pluck(value, 'food')
}
})
.value();
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 17
不使用下划线:
var origArr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'}
];
/*[
{type: 'fruit', foods: ['apple', 'banana']},
{type: 'vegetable', foods: ['potato']}
]*/
function transformArr(orig) {
var newArr = [],
types = {},
i, j, cur;
for (i = 0, j = orig.length; i < j; i++) {
cur = orig[i];
if (!(cur.type in types)) {
types[cur.type] = {type: cur.type, foods: []};
newArr.push(types[cur.type]);
}
types[cur.type].foods.push(cur.food);
}
return newArr;
}
console.log(transformArr(origArr));
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/ErikE/nSLua/3/
幸得@ErikE为提高/降低我的原代码,以帮助冗余我不得不:)
这是@ Ian的答案略有不同但更通用的版本
警告:结果与OP要求略有不同,但像我这样偶然发现这个问题的其他人可能会受益于更通用的答案恕我直言
var origArr = [
{food: 'apple', type: 'fruit'},
{food: 'potato', type: 'vegetable'},
{food: 'banana', type: 'fruit'}
];
function groupBy(arr, key) {
var newArr = [],
types = {},
newItem, i, j, cur;
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!(cur[key] in types)) {
types[cur[key]] = { type: cur[key], data: [] };
newArr.push(types[cur[key]]);
}
types[cur[key]].data.push(cur);
}
return newArr;
}
console.log(groupBy(origArr, 'type'));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32196 次 |
最近记录: |