将多个对象合并为一个对象并合并JavaScript属性
我在数组中有多个对象,我想合并具有相同id的所有对象,但是我也想合并一个属性的所有值(在这种情况下,是通道)
这是代码:
defaultArray = [
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
预期输出:
newArray = [
{
id: "FirstId",
name: "Some random name"
channels: [
{
id: "Channel-ASD",
name: "Channel ASD"
},
{
id: "Channel-QWE",
name: "Channel QWE"
}
]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
]
回答如下:您需要研究filter
,map
,reduce
,some
,...
let defaultArray = [
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name",
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
let transformed= defaultArray.reduce((result, item, index, original)=>{
if (result.some(i=>i.id===item.id)) return result;
let channels = original.reduce((r,i)=>{
i.id===item.id && (r=[...r, ...i.channels]);
return r;
},[]);
result.push({
...item,
channels
});
return result;
},[]);
console.log(JSON.stringify(transformed,null,2));
将多个对象合并为一个对象并合并JavaScript属性
我在数组中有多个对象,我想合并具有相同id的所有对象,但是我也想合并一个属性的所有值(在这种情况下,是通道)
这是代码:
defaultArray = [
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
预期输出:
newArray = [
{
id: "FirstId",
name: "Some random name"
channels: [
{
id: "Channel-ASD",
name: "Channel ASD"
},
{
id: "Channel-QWE",
name: "Channel QWE"
}
]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
]
回答如下:您需要研究filter
,map
,reduce
,some
,...
let defaultArray = [
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name",
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
let transformed= defaultArray.reduce((result, item, index, original)=>{
if (result.some(i=>i.id===item.id)) return result;
let channels = original.reduce((r,i)=>{
i.id===item.id && (r=[...r, ...i.channels]);
return r;
},[]);
result.push({
...item,
channels
});
return result;
},[]);
console.log(JSON.stringify(transformed,null,2));
发布评论