对不起,标题。我什至不知道该如何解释自己想要的东西。
这就是我要实现的目标
const array = [
{
key: 0,
key2: [ { id: "a", data: "abc" }, { id: "b", data: "wxy" }... ]
},
{
key: 1,
key2: [ { id: "a", data: "qwe" }, { id: "b", data: "zxc" }... ]
},
...
]
我想将其转换为
const result = {
0 : {
a: "abc",
b: "wxy"
},
1 : {
a: "qwe",
b: "zxc"
}
}
到目前为止,我有这个:
const transforms = array
.map((o) => {
return { [o.key]: o.key2 };
})
.reduce((prev, curr) => {
for (let key in curr)
prev[key] = curr[key]
.map((c) => {
return { [c.id]: c.data};
})
.reduce((prev, curr) => {
for (let key in curr) prev[key] = curr[key];
return prev;
}, {});
return prev;
}, {});
很难读的书,可能不是很出色。 老实说,我什至不知道它是否真的100%有效。 到目前为止,它给了我预期的结果。
我该如何重构? 请帮忙。
答案 0 :(得分:4)
您的任务可以有效地分解为4个小问题:
id
/ data
组合中取出键/值对,可以使用computed property names key2.map(({id,data}) => ({[id]:data}))
Object.assign()
Object.assign({}, ...key2.map(({id,data}) => ({[id]:data})))
Array.prototype.map()
将您的源数组项转换为新的数组,其中包含转换后的key2
src.map(({key2}) =>
Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
{...result} = src.map(({key2}) =>
Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
生成的代码更加紧凑和works noticeably faster
您可以找到现场演示,如下所示:
const src = [{key:0,key2:[{id:"a",data:"abc"},{id:"b",data:"wxy"}]},{key:1,key2:[{id:"a",data:"qwe"},{id:"b",data:"zxc"}]}],
{...result} = src.map(({key2}) =>
Object.assign({}, ...key2.map(({id,data}) => ({[id]:data}))))
console.log(result)
.as-console-wrapper{min-height:100%;}
答案 1 :(得分:0)
const array = [
{
key: 0,
key2: [ { id: "a", data: "abc" }, { id: "b", data: "wxy" }]
},
{
key: 1,
key2: [ { id: "a", data: "qwe" }, { id: "b", data: "zxc" }]
},
]
const result = array.reduce((res, entry) => {
return Object.assign(res, { [entry.key]: entry.key2.reduce((data, current) => {
return Object.assign(data, { [current.id]: current.data })
}, {}) });
}, {})
console.log(result)
转换功能
array.reduce((res, entry) => {
return Object.assign(res, { [entry.key]: entry.key2.reduce((data, current) => {
return Object.assign(data, { [current.id]: current.data })
}, {}) });
}, {})