gpt4 book ai didi

javascript - 比较两个数组,如果发现相同的键,则从第二个数组中获取值

转载 作者:行者123 更新时间:2023-12-01 04:00:47 25 4
gpt4 key购买 nike

如何比较两个数组,如果找到相同的键,则从第二个数组中获取值并将其分配给第一个数组。结果是使用第一个数组。例如我有下面的数组:

    var compareit = {
firstArray : {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};

目标是,我想要的结果是:{'color': 'red', 'width': '400', 'height': '500'};

我非常感谢您的帮助...谢谢:)

最佳答案

您可以使用 Object.assign()将值从一个或多个源对象复制到目标对象。

 var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};

Object.assign(compareit.firstArray, compareit.secondArray);
console.log(compareit.firstArray)

如果你不想操作现有对象compareit.firstArray

var compareit = {
firstArray: {
'color': 'blue',
'width': 400,
'height': 150,
},
secondArray: {
'color': 'red',
'height': 500,
},
};

var obj = {};
Object.assign(obj, compareit.firstArray, compareit.secondArray);
console.log(obj, compareit)

关于javascript - 比较两个数组,如果发现相同的键,则从第二个数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42201363/

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