gpt4 book ai didi

javascript - 将对象数组转换为对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:49:09 26 4
gpt4 key购买 nike

我有一个分支数组,大致如下所示:

let branches = [
{
id: 21,
name: "Branch 1",
opening_times: [ {}, {}, {} ] // Array of objects (Monday, Tuesday etc)
},
{
id: 22,
name "Branch 2"
opening_times: [ {}, {}, {} ] // Array of objects (Monday, Tuesday etc)
},
// .. etc
]

但我想把它变成一个对象,名称作为每个对象的键。

期望的输出:

branches = {
"Branch 1": {
id: 21,
opening_times: [ {}, {}, {} ] // Array of objects (Monday, Tuesday etc)
},
"Branch 2": {
id: 22,
opening_times: [ {}, {}, {} ] // Array of objects (Monday, Tuesday etc)
}
}

尝试过:

let newBranches = branches.map(branch => (
{
[branch.name]: {
id: branch.id,
days: branch.opening_times
}
}
));
console.log(newBranches)

当然,映射会给我一个数组输出:

[
0: {Branch 1: {…}}
1: {Branch 2: {…}}
]

任何人都可以帮助我指明正确的方向,以获取一个具有 name 键的新对象作为对象本身吗?

最佳答案

通过简单的 reduce() 操作和对象解构:

const branches = [{
id: 21,
name: "Branch 1",
opening_times: []
},
{
id: 22,
name: "Branch 2",
opening_times: []
}
];

const result = branches.reduce((a, {name, ...v}) => (a[name] = v, a), {});

console.log(result);

关于javascript - 将对象数组转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439738/

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