Eli*_*han 3 javascript arrays object ecmascript-6
我有一个分支数组,看起来像这样:
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
]
Run Code Online (Sandbox Code Playgroud)
但我想将其变成一个对象,每个对象的名称均作为关键字。
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)
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
但是当然映射给了我一个数组输出:
let newBranches = branches.map(branch => (
{
[branch.name]: {
id: branch.id,
days: branch.opening_times
}
}
));
console.log(newBranches)
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我指出正确的方向,以将name密钥作为对象本身来获得一个新对象吗?
我只是使用一个简单的for-of循环。您会得到reduce答案,但是reduce这里所做的只是增加了复杂性。
const result = {};
for (const {name, id, opening_times} of branches) {
result[name] = {id, opening_times};
}
Run Code Online (Sandbox Code Playgroud)
现场示例:
const result = {};
for (const {name, id, opening_times} of branches) {
result[name] = {id, opening_times};
}
Run Code Online (Sandbox Code Playgroud)
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
];
const result = {};
for (const {name, id, opening_times} of branches) {
result[name] = {id, opening_times};
}
console.log(result);Run Code Online (Sandbox Code Playgroud)
补充Code Maniac关于使用休息的建议:
const result = {};
for (const {name, ...entry} of branches) {
result[name] = entry;
}
Run Code Online (Sandbox Code Playgroud)
现场示例:
.as-console-wrapper {
max-height: 100% !important;
}Run Code Online (Sandbox Code Playgroud)
const result = {};
for (const {name, ...entry} of branches) {
result[name] = entry;
}
Run Code Online (Sandbox Code Playgroud)
两者略有不同,因为第一个显式仅使用id和opening_times结果,而其余版本使用以外的所有属性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);Run Code Online (Sandbox Code Playgroud)