比较两个对象数组

时间:2017-01-25 10:56:39

标签: javascript arrays

我有两个像这样的阵列。第一个数组是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"
   }
]

第二个是field,长度是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字段比较这些数组,并将{01}数组中的customFields数组添加到缺少的对象中。如果没有2个for循环互相循环,我怎么能做到这一点。什么是最有效的方式。谢谢!!!!

3 个答案:

答案 0 :(得分:4)

您可以使用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)

答案 1 :(得分:1)

您可以使用原生高阶函数,例如map和reduce。

使用lodash的示例实现在这里。 https://github.com/rbs392/object-deep-diff/blob/master/index.js

答案 2 :(得分:0)

这是一个没有嵌套循环的解决方案。首先,生成包含customFields数组的ID的查找表。接下来遍历field数组,并将每个缺少的对象附加到customFields数组。查找表也会更新,以处理可能的重复项。

var lut = customFields.map(function(obj) {
  return obj.id;
});
field.forEach(function(obj) {
  if (lut.indexOf(obj.id) == -1) {
    customFields.push(obj);
    lut.push(obj.id);
  }
});

如评论中所述,我的第一个命题隐藏了indexOf中的复杂性。

这是一种替代方法,它依赖于ID查找的对象属性,这可能比线性搜索更好。 lut维护从ID到customFields数组索引的关联。

var lut = customFields.reduce(function(t, obj, i) {
  t[obj.id] = i;
  return t;
}, {});
field.forEach(function(obj) {
  if (undefined === lut[obj.id]) {
    lut[obj.id] = customFields.push(obj) - 1;
  }
});