gpt4 book ai didi

javascript - 如何连接对象

转载 作者:行者123 更新时间:2023-11-28 13:16:14 25 4
gpt4 key购买 nike

给定以下两个对象数组:

var items = [
{colorId:'2',name:'qqq'},
{colorId:'5',name:'www'},
{colorId:'2',name:'eee'},
{colorId:'4',name:'rrr'}
];

var colors = [
{id:'5',name:'blue'},
{id:'2',name:'red'}
];

我需要根据 colorIditemscolors 之间建立连接。

期望的结果:

var arr3 = [
{id:'2', name:'qqq', name:'red'},
{id:'5', name:'www', name:'blue'},
{id:'2', name:'eee', name:'red'}
];

执行此操作的优雅方法是什么?

最佳答案

这是一个纯 JavaScript 解决方案,它将更改 items 数组本身。

如果您不想修改同一个数组,可以创建新数组并将克隆项插入其中。

var items= [{colorId:'2',name:'qqq'}, 
{colorId:'5',name:'www'},
{colorId:'2',name:'eee'},
{colorId:'4',name:'rrr'}]


var colors= [{id:'5',name:'blue'},
{id:'2',name:'red'}, ]

items.forEach(function(d) {
var matchColor = colors.filter(function(item){ return item.id === d.colorId});
if(matchColor.length){
d.color = matchColor[0].name;
}
});

console.log(items);

关于javascript - 如何连接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37907256/

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