gpt4 book ai didi

javascript - JS : Reduce array to nested objects

转载 作者:行者123 更新时间:2023-11-29 20:58:42 25 4
gpt4 key购买 nike

所以我有这个数组

var mapped = [[2016, "October", "Monday", {object}], [2017, "January", "Friday", {object}], [2017, "January", "Wednesday", {object}], [2017, "October", "Monday", {object}]]

我想要完成的是这样的:

[{
"2016": [{
"October": [{
"Monday": [{object}]
}]
}],
}, {
"2017": [{
"January": [{
"Friday": [{object}]
}, {
"Wednesday": [{object}]
}]
}, {
"October": [{
"Monday": [{object}]
}]
}]
}]

我已经搜索了很长时间,但找不到解决方案。通过使用 reduce,我得到了这样的结果:

[
2016: [{
"month": "October"
}]
],
[
2017: [{
"month": "January"
},
{
"month": "January"
},
{
"month": "September"
}]
]

所以看起来我很感兴趣,但还很遥远......这就是我正在做的:

mapped.reduce((years, array) => {

years[array[0]] = years[array[0]] || [];

years[array[0]].push({
month: array[1]
})

return years;

}, [])

最佳答案

不完全是你指定的,但我觉得下面的脚本输出一种最有用的格式——它只在最深的层次上产生数组:

const  mapped = [[2016, "October", "Monday", { a: 1 }], [2017, "January", "Friday", { a: 1 }], [2017, "January", "Wednesday", { a: 1 }], [2017, "October", "Monday", { a: 1 }]];

const result = mapped.reduce( (acc, [year, month, day, object]) => {
let curr = acc[year] = acc[year] || {};
curr = curr[month] = curr[month] || {};
curr = curr[day] = curr[day] || [];
curr.push(object);
return acc;
}, {});

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

用数组环绕

如果你真的需要包装数组,你可以对之前的结果应用一个额外的递归函数:

const  mapped = [[2016, "October", "Monday", { a: 1 }], [2017, "January", "Friday", { a: 1 }], [2017, "January", "Wednesday", { a: 1 }], [2017, "October", "Monday", { a: 1 }]];

const result = mapped.reduce( (acc, [year, month, day, object]) => {
let curr = acc[year] = acc[year] || {};
curr = curr[month] = curr[month] || {};
curr = curr[day] = curr[day] || [];
curr.push(object);
return acc;
}, {});

function wrapInArrays(data) {
return Array.isArray(data) ? data
: Object.entries(data).map ( ([key, value]) => {
return { [key]: wrapInArrays(value) };
});
}

const wrapped = wrapInArrays(result);
console.log(wrapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - JS : Reduce array to nested objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com