我有一系列项目,我从API获得作为响应主体。
data = [{id: 1, category: "kitchen", name: "noodles"},
{id: 2, category: "general", name: "Wi-Fi"},
{id: 3, category: "sports", name: "Football"},]
我想迭代数组,并获得如下数据:
var categorized = {
kitchen: [{id: 1, category: "kitchen", name: "noodles"}],
general : [{id: 2, category: "general", name: "Wi-Fi"}],
sports : [{id: 3, category: "sports", name: "Football"}]
};
是否有任何lodash方法或任何ES6快捷方式?
答案 0 :(得分:4)
回答你的问题'有一种lodash方法吗?'是的:https://lodash.com/docs/4.17.4#groupBy。对于您的具体示例:
const categorized = _.groupBy(data, 'category');
编辑:您可以使用ES6滚动自己的groupBy类型函数,如另一个示例所示。但是,如果你使用lodash,那么这将更加清洁。
答案 1 :(得分:2)
我使用array.reduce
来获取结构
var data = [{
id: 1,
category: "kitchen",
name: "noodles"
}, {
id: 2,
category: "general",
name: "Wi-Fi"
}, {
id: 3,
category: "sports",
name: "Football"
}]
var newData = data.reduce(function(obj, v, i) {
obj[v.category] = obj[v.category] || [];
obj[v.category].push(v);
return obj;
}, {});
console.log(newData);
在ES6中你可以这样使用:
var newData = data.reduce((obj, v, i)=> {
obj[v.category] = obj[v.category] || [];
obj[v.category].push(v);
return obj;
}, {});
console.log(newData);