gpt4 book ai didi

javascript - 按键组合两个对象数组,并将第二个数组的值插入第一个数组内的新数组

转载 作者:行者123 更新时间:2023-11-30 21:01:51 26 4
gpt4 key购买 nike

我需要一个包含两个数组数据的结果数组。如果名称相同,则将第二个数组的值添加到第一个数组的数组中。执行此操作的最佳方法是什么?

var array1 = [
{name: "name1", type: "type"},
{name: "name2", type: "type"},
{name: "name3", type: "type"}
]

var array2 = [
{name: "name1", value: "value1"},
{name: "name2", value: "value2"},
{name: "name2", value: "value3"},
{name: "name2", value: "value4"}
]

var result = [
{name: "name1", type: "type", values: [
"value1"
]},
{name: "name2", type: "type", values: [
"value2",
"value3",
"value4"
]},
{name: "name3", type: "type", values:[]}
]

最佳答案

这是我的方法(注意它修改了array1):

var array1 = [
{name: "name1", type: "type"},
{name: "name2", type: "type"},
{name: "name3", type: "type"}
]

var array2 = [
{name: "name1", value: "value1"},
{name: "name2", value: "value2"},
{name: "name2", value: "value3"},
{name: "name2", value: "value4"}
]

var result = array1.map(item => {
item.values = array2
.filter(x => x.name === item.name)
.map(x => x.value)

return item
})

console.log(result)

关于javascript - 按键组合两个对象数组,并将第二个数组的值插入第一个数组内的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066015/

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