我有以下内容:
[
{year: 2017, week: 45},
{year: 2017, week: 46},
{year: 2017, week: 47},
{year: 2017, week: 48},
{year: 2017, week: 50},
{year: 2017, week: 52},
{year: 2018, week: 1},
{year: 2018, week: 2},
{year: 2018, week: 5}
]
但是希望按年将其分组为以下格式:
[
{ 2017 : [{
label: 45, value: 45,
label: 46, value: 46,
label: 47, value: 47,
label: 48, value: 48,
etc
},
{ 2018 : [{
label: 1, value: 1,
label: 2, value: 2,
etc
}]
]
使用Javascript(ES6)执行此操作的最佳方法是什么?我也可以使用lodash / underscore库。
答案 0 :(得分:1)
使用reduce
var output = arr.reduce((a, b) => ((a[b.year] = a[b.year] || []).push({
label: b.week,
val: b.week
}), a), {});
<强>演示强>
var arr = [{
year: 2017,
week: 45
},
{
year: 2017,
week: 46
},
{
year: 2017,
week: 47
},
{
year: 2017,
week: 48
},
{
year: 2017,
week: 50
},
{
year: 2017,
week: 52
},
{
year: 2018,
week: 1
},
{
year: 2018,
week: 2
},
{
year: 2018,
week: 5
}
];
var output = arr.reduce((a, b) => (a[b.year] = a[b.year] || [], a[b.year].push({
label: b.week,
val: b.week
}), a), {});
console.log(output);
&#13;
答案 1 :(得分:1)
您可以使用哈希表并使用对数组的引用来插入新对象。
var data = [{ year: 2017, week: 45 }, { year: 2017, week: 46 }, { year: 2017, week: 47 }, { year: 2017, week: 48 }, { year: 2017, week: 50 }, { year: 2017, week: 52 }, { year: 2018, week: 1 }, { year: 2018, week: 2 }, { year: 2018, week: 5 }],
hash = Object.create(null),
result = [];
data.forEach(function (o) {
var temp = {};
if (!hash[o.year]) {
hash[o.year] = [];
temp[o.year] = hash[o.year];
result.push(temp);
}
hash[o.year].push({ label: o.week, value: o.week });
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
它会对你有所帮助
var arr=[
{year: 2017, week: 45},
{year: 2017, week: 46},
{year: 2017, week: 47},
{year: 2017, week: 48},
{year: 2017, week: 50},
{year: 2017, week: 52},
{year: 2018, week: 1},
{year: 2018, week: 2},
{year: 2018, week: 5}
]
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var arr_res=groupBy(arr, 'year')
console.log(arr_res);
答案 3 :(得分:0)
您可以使用.reduce
和Array.from
:
我已经对您的要求做出了假设,因为您要求的内容不是有效对象。
const res = Array.from(arr.reduce((accum, val) => {
const grouping = accum.get(val.year) || [];
grouping.push({ label: val.week, value: val.week });
accum.set(val.year, grouping);
return accum;
}, new Map()), kv => ({ [kv[0]]: kv[1] }));
console.log(JSON.stringify(res, null, 2));