gpt4 book ai didi

javascript - 对象的嵌套reduce函数

转载 作者:行者123 更新时间:2023-12-01 15:32:52 24 4
gpt4 key购买 nike

我正在尝试减少已经减少的数组,并且在第二次减少功能后我的对象出现问题。我在第二个函数运行之前的对象如下所示:

const object = {
groupA: [
{name: "Adam", age: 25, Job: "Pharmacist", group: 'groupA'},
{name: "Eric", age: 25, Job: "Vet", group: 'groupA'},
{name: "Bob", age: 25, Job: "Pharmacist", group: 'groupA'},
{name: "Peter", age: 25, Job: "Vet", group: 'groupA'},
],
groupB: [
{name: "Adam", age: 25, Job: "Pharmacist", group: 'groupB'},
{name: "Eric", age: 25, Job: "Vet", group: 'groupB'},
{name: "Bob", age: 25, Job: "Pharmacist", group: 'groupB'},
{name: "Peter", age: 25, Job: "Vet", group: 'groupB'},
],


}

如果我想得到这样的结果,我应该使用什么函数。


const object = {
groupA: {
pharmacist: [
{name: "Adam", age: 25, Job: "Pharmacist", group: 'groupA'},
{name: "Bob", age: 25, Job: "Pharmacist", group: 'groupA'},
],
vet: [
{name: "Eric", age: 25, Job: "Vet", group: 'groupA'},
{name: "Peter", age: 25, Job: "Vet", group: 'groupA'},
]
},
groupB: {
pharmacist: [
{name: "Adam", age: 25, Job: "Pharmacist", group: 'groupB'},
{name: "Bob", age: 25, Job: "Pharmacist", group: 'groupB'},
],
vet: [
{name: "Eric", age: 25, Job: "Vet", group: 'groupB'},
{name: "Peter", age: 25, Job: "Vet", group: 'groupB'},
]
},


}

最佳答案

您可以创建一个单独的函数来 reduce() 每个组,然后使用 for..in 将每个组的未缩减数组替换为缩减对象

const object = {"groupA":[{"name":"Adam","age":25,"Job":"Pharmacist","group":"groupA"},{"name":"Eric","age":25,"Job":"Vet","group":"groupA"},{"name":"","age":25,"Job":"Pharmacist","group":"groupA"},{"name":"","age":25,"Job":"Vet","group":"groupA"}],"groupB":[{"name":"Adam","age":25,"Job":"Pharmacist","group":"groupB"},{"name":"Eric","age":25,"Job":"Vet","group":"groupB"},{"name":"","age":25,"Job":"Pharmacist","group":"groupB"},{"name":"","age":25,"Job":"Vet","group":"groupB"}]}

function groupByJob(arr){
return arr.reduce((ac, a) => {
if(!ac[a.Job]){
ac[a.Job] = [];
}
ac[a.Job].push(a);
return ac;
}, {});
}

for(let k in object){
object[k] = groupByJob(object[k]);
}
console.log(object)

如果您不想拆分,可以直接将 map() 应用于 object 的条目,然后直接在 map() 上使用每个值。

const object = {"groupA":[{"name":"Adam","age":25,"Job":"Pharmacist","group":"groupA"},{"name":"Eric","age":25,"Job":"Vet","group":"groupA"},{"name":"","age":25,"Job":"Pharmacist","group":"groupA"},{"name":"","age":25,"Job":"Vet","group":"groupA"}],"groupB":[{"name":"Adam","age":25,"Job":"Pharmacist","group":"groupB"},{"name":"Eric","age":25,"Job":"Vet","group":"groupB"},{"name":"","age":25,"Job":"Pharmacist","group":"groupB"},{"name":"","age":25,"Job":"Vet","group":"groupB"}]}

const res = Object.fromEntries(
Object.entries(object)
.map(([k, v]) =>
[
k,
v.reduce((ac, a) =>
(ac[a.Job] = (ac[a.Job] || []).concat(a), ac),
{})
]
)
)

console.log(res)

关于javascript - 对象的嵌套reduce函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740940/

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