gpt4 book ai didi

javascript - 合并两个具有不同键但相同值的无序对象?

转载 作者:行者123 更新时间:2023-12-03 03:38:53 25 4
gpt4 key购买 nike

在 JavaScript 中合并 obj1 和 obj2 等对象以获取 obj3。

obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}]
obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}]

obj3 = [{fruit_name: 'apple', color: 'red', sweetness: 5},{fruit_name: 'banana', color:'yellow', sweetness: 4},{fruit_name: 'watermelon', color:'green', sweetness: 3}]

最佳答案

不是通用解决方案,但足以满足您的情况:

var obj1 = [{fruit: 'watermelon', sweetness: 3},{fruit: 'banana', sweetness: 4},{fruit: 'apple', sweetness: 5}]
var obj2 = [{fruit_name: 'apple', color: 'red'},{fruit_name: 'banana', color:'yellow'},{fruit_name: 'watermelon', color:'green'}]

var obj3 = obj2.map(o => Object.assign({}, o, {'sweetness': obj1.find(p => p.fruit === o.fruit_name).sweetness}))

console.log(obj3)

关于javascript - 合并两个具有不同键但相同值的无序对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725142/

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