Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two arrays of objects

i have two arrays like this. first array is customFields and length is 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"
   }
]

second one is field and length is 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"
   }
] 

both arrays are dynamic and i need to compare these arrays by id fields and add missing objects to customFields array from field array. how can i do this without 2 for loops looping inside one another. what is the most efficient way. thank you !!!!

like image 805
Sachila Ranawaka Avatar asked Feb 05 '23 06:02

Sachila Ranawaka


1 Answers

You can use reduce() and find() to get desired result.

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)
like image 119
Nenad Vracar Avatar answered Feb 07 '23 19:02

Nenad Vracar