gpt4 book ai didi

javascript - 根据 props 上的匹配集向元素数组添加属性 - es6

转载 作者:行者123 更新时间:2023-11-28 14:44:41 24 4
gpt4 key购买 nike

我有以下对象数组:

 arr = [
{
connectors:[
{source: "aaaa", target: "bbbb"}
{source: "bbbb", target: "2222"}
{source: "aaaa", target: "cccc"}
{source: "cccc", target: "1111"}
],
connections: [
{name: "aaaa", id: "11", type: "main"}
{name: "bbbb", id: "22", type: "submain"}
{name: "2222", id: "33", type: "supersubmain"}
{name: "cccc", id: "44", type: "submain"}
{name: "1111", id: "55", type: "supersubmain"}
]
}
]

我需要根据与连接器数组匹配的键值对向数组添加额外的属性。

条件主要是if(connectors.source ===connections.name &&connections.type ==='main'),那么我需要将connect属性添加到连接器数组中如下图所示。

我想要以下输出:

 arr = [
{
connectors:[
{source: "aaaa", target: "bbbb", connect: true}
{source: "bbbb", target: "2222", connect: false}
{source: "aaaa", target: "cccc", connect: true}
{source: "cccc", target: "1111", connect: false}
],
connections: [
{name: "aaaa", id: "11", type: "main"}
{name: "bbbb", id: "22", type: "submain"}
{name: "2222", id: "33", type: "supersubmain"}
{name: "cccc", id: "44", type: "submain"}
{name: "1111", id: "55", type: "supersubmain"}
]
}
]

我尝试过使用不同的 es6 函数的组合,如 map、filter、spread,但找不到合适的解决方案。

提前致谢。

最佳答案

您可以使用 forEach() 循环每个对象,并使用 some 检查条件并添加 connect 值。

var arr = [{"connectors":[{"source":"aaaa","target":"bbbb"},{"source":"bbbb","target":"2222"},{"source":"aaaa","target":"cccc"},{"source":"cccc","target":"1111"}],"connections":[{"name":"aaaa","id":"11","type":"main"},{"name":"bbbb","id":"22","type":"submain"},{"name":"2222","id":"33","type":"supersubmain"},{"name":"cccc","id":"44","type":"submain"},{"name":"1111","id":"55","type":"supersubmain"}]}]

arr.forEach(function(c) {
c.connectors.forEach(function(a) {
var connect = c.connections.some(function(e) {
return e.name == a.source && e.type == 'main'
})
a.connect = connect;
})
})


console.log(arr)

关于javascript - 根据 props 上的匹配集向元素数组添加属性 - es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831829/

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