gpt4 book ai didi

javascript - 比较两个对象数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:06 25 4
gpt4 key购买 nike

我有两个这样的数组。第一个数组是 customFields,长度是 2

var customFields = [  
{
"$$hashKey":"object:259",
"fields":[

],
"id":0.84177744416334,
"inputType":"number",
"labelShown":"item",
"type":"textBox",
"value":"222222"
},
{
"$$hashKey":"object:260",
"fields":[
"as",
"dd",
"asd"
],
"id":0.51091342118417,
"inputType":"",
"labelShown":"labels",
"type":"selectBox",
"value":"dd"
}
]

第二个是字段,长度是3

var field = [  
{
"fields":[

],
"id":0.84177744416334,
"inputType":"number",
"labelShown":"item",
"type":"textBox"
},
{
"fields":[
"as",
"dd",
"asd"
],
"id":0.51091342118417,
"inputType":"",
"labelShown":"labels",
"type":"selectBox"
},
{
"fields":[

],
"id":0.32625015743856,
"inputType":"text",
"labelShown":"sample",
"type":"textBox"
}
]

这两个数组都是动态的,我需要通过 id 字段比较这些数组,并将缺少的对象从 field 数组添加到 customFields 数组。如果没有 2 个 for 循环在另一个内部循环,我怎么能做到这一点。什么是最有效的方法。谢谢!!!!

最佳答案

您可以使用 reduce()find() 来获得所需的结果。

var customFields = [{"$$hashKey":"object:259","fields":[],"id":0.84177744416334,"inputType":"number","labelShown":"item","type":"textBox","value":"222222"},{"$$hashKey":"object:260","fields":["as","dd","asd"],"id":0.51091342118417,"inputType":"","labelShown":"labels","type":"selectBox","value":"dd"}];
var field = [{"fields":[],"id":0.84177744416334,"inputType":"number","labelShown":"item","type":"textBox"},{"fields":["as","dd","asd"],"id":0.51091342118417,"inputType":"","labelShown":"labels","type":"selectBox"},{"fields":[],"id":0.32625015743856,"inputType":"text","labelShown":"sample","type":"textBox"}]

var result = field.reduce(function(r, e) {
var f = customFields.find(el => e.id == el.id)
r.push(f ? f : e)
return r;
}, [])

console.log(result)

关于javascript - 比较两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849757/

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