我正在尝试按日期对数组中的对象进行分组:
var list = [
{
date: "2017-01-01",
type: "type1",
amount: 100
},
{
date: "2017-01-01",
type: "type2",
amount: 150
},
{
date: "2017-01-02",
type: "type1",
amount: 200
}
]
我正试图得到类似的东西:
var dateArr = [
{
date: "2017-01-01",
activities: [
{
type: "type1",
amount: 100
},
{
type: "type2",
amount: 150
}]
}
]
我尝试过一些事情......比如使用下划线(来自这里https://stackoverflow.com/a/15888912/4989305):
var dateArr = _
.chain(list)
.groupBy('date')
.map(function(value, key) {
return {
date: key,
activities: [{
type: _.pluck(value, 'type'),
amount: _.pluck(value, 'amount')
}]
}
})
.value();
我也试过这个(从这里https://stackoverflow.com/a/31373860/4989305)
var dateArr = {};
list.forEach(function(item){
dateArr[item.date] = dateArr[item.date]||[];
dateArr[item.date].push(item);
});
但是,由于某些原因,两者都返回空白。
非常感谢任何帮助。
答案 0 :(得分:9)
几行现代JavaScript将为您提供所需的结果:
var dateArr = Object.values(list.reduce((result, {
date,
type,
amount
}) => {
// Create new group
if (!result[date]) result[date] = {
date,
activities: []
};
// Append to group
result[date].activities.push({
type,
amount
});
return result;
}, {}));
阐释:
Array.reduce
将列表合并为一组结果,一个普通的对象,按日期分组。reduce
,以便下一个项目合并到同一套装中。Object.values
从集合中提取值。 (放下钥匙)答案 1 :(得分:4)
您可以按日期为groupiung使用哈希表,并将单个组分配给结果数组。
var list = [{ date: "2017-01-01", type: "type1", amount: 100 }, { date: "2017-01-01", type: "type2", amount: 150 }, { date: "2017-01-02", type: "type1", amount: 200 }],
result = [];
list.forEach(function (hash) {
return function (a) {
if (!hash[a.date]) {
hash[a.date] = { date: a.date, activities: []};
result.push(hash[a.date]);
}
hash[a.date].activities.push({ type: a.type, amount: a.amount });
};
}(Object.create(null)));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:3)
我希望这是你真正需要的。
var list = [
{
date: "2017-01-01",
type: "type1",
amount: 100
},
{
date: "2017-01-01",
type: "type2",
amount: 150
},
{
date: "2017-01-02",
type: "type1",
amount: 200
}
]
var dateArrKeyHolder = [];
var dateArr = [];
list.forEach(function(item){
dateArrKeyHolder[item.date] = dateArrKeyHolder[item.date]||{};
var obj = dateArrKeyHolder[item.date];
if(Object.keys(obj).length == 0)
dateArr.push(obj);
obj.date = item.date;
obj.activities = obj.activities || [];
obj.activities.push({type:item.type, amount: item.amount });
});
console.log(JSON.stringify(dateArr));