gpt4 book ai didi

javascript - 如何在两个对象数组之间建立交集

转载 作者:行者123 更新时间:2023-11-29 15:09:04 25 4
gpt4 key购买 nike

我正在尝试在两个对象数组之间进行交集。

https://codesandbox.io/s/friendly-bohr-v73ob?fbclid=IwAR3yQDnftREENi8lF6wCKYE_F09pimlLgfYca0B_oIPqYYHvbAf4cvnG-n4

const list1 = [
{
name: "skinType",
keys: [
{
id: "oily",
label: "Oily"
},
{
id: "dry",
label: "Dry"
}
]
},
{
name: "finish",
keys: [
{
id: "oily",
label: "Oily"
},
{
id: "dry",
label: "Dry"
},
{
id: "matte",
label: "Matte"
},
{
id: "natural",
label: "Natural"
},
{
id: "radiant",
label: "Radiant / Glow"
}
]
},
{
name: "texture",
keys: [
{
id: "matte",
labal: "Matte"
}
]
}
];

const list2 = [
{
name: "skinType",
keys: [
{
id: "oily",
label: "Oily"
},
{
id: "dry",
label: "Dry"
},
{
id: "gandac",
label: "mazga"
}
]
},
{
name: "finish",
keys: [
{
id: "oily",
label: "Oily"
}
]
}
];

我想出了一个解决方案,但它只能根据对象的名称键进行交集。现在我需要根据键数组中的 id 进行交集。

const intersection = (list1, list2) => {
return list2.filter(drp => list1.some(rect => rect.name === drp.name));
};

const result = intersection(react, drupal);

预期结果:

[
{
name: "skinType",
keys: [
{
id: "oily",
label: "Oily"
},
{
id: "dry",
label: "Dry"
}
]
},
{
name: "finish",
keys: [
{
id: "oily",
label: "Oily"
}
]
}
]

最佳答案

const react = [
{ name: "skinType",
keys: [
{ id: "oily", label: "Oily" },
{ id: "dry", label: "Dry" }
]
},
{ name: "finish",
keys: [
{ id: "oily", label: "Oily" },
{ id: "dry", label: "Dry" },
{ id: "matte", label: "Matte" },
{ id: "natural", label: "Natural" },
{ id: "radiant", label: "Radiant / Glow" }
]
},
{ name: "texture",
keys: [
{ id: "matte", labal: "Matte" }
]
}
];

const drupal = [
{ name: "skinType",
keys: [
{ id: "oily", label: "Oily" },
{ id: "dry", label: "Dry" },
{ id: "gandac", label: "mazga" }
]
},
{ name: "finish",
keys: [
{ id: "oily", label: "Oily" }
]
}
];

var result = [];
for(var item1 of react)
for(var item2 of drupal)
if(item1.name == item2.name){
var keys = item2.keys.filter(x => item1.keys.some(y => y.id === x.id));
result.push({name: item1.name, keys})
break;
}
console.log(result);

关于javascript - 如何在两个对象数组之间建立交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784421/

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