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 !!!!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With