Reputation: 153
My problem is that:
I have got 2 Array objects like that
var array1 = [{ "id": 1, "name": "potatoe", photo="photo"}, {"id": 2, "name": "budget"}]
var array2 = [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name":
"UhOhAnotherName"}, {"id": 2, "name": "budget"}]
I want to search if array1 ID object is in array 2, if is id 1 = 1 name will be replaced, If no exist like id 3 will be added.
The result will be
[{ "id": 1, "name": "potatoeModified", photo="photo"}, {"id": 2, "name": "budget"},
{ "id": 3, "name": "UhOhAnotherName"}]
I try to do that but all times I get one function with cyclomatic complexity is too high and I don't want one Super Big function for that. I think that the solution is simple but I'm so blind..... Thanks :)
Upvotes: 1
Views: 69
Reputation: 171669
I would make a temporary object from each array that uses the id's as keys and stores each item as value.
Then you can loop through array 2 temporary object and either adjust name or push to array 1 depending on whether id key exist in temporary object one
var array1 = [{ "id": 1, "name": "potatoe", photo:"photo"}, {"id": 2, "name": "budget"}];
var array2 = [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name":
"UhOhAnotherName"}, {"id": 2, "name": "budget"}];
// create temporary objects using helper function below
var tmp_1 = toObj(array1),
tmp_2 = toObj(array2);
// go through array 2 temp object and either adjust name or push to array 1
Object.keys(tmp_2).forEach((key)=>{
if(tmp_1[key]){
// if same id exist from array one, set name
tmp_1[key].name = tmp_2[key].name;
}else{
// push to array one when same id doesn't exist
array1.push(tmp_2[key]);
}
});
console.log(array1);
// helper function to prevent code duplication
function toObj(arr){
return arr.reduce((a,c)=>{
a[c.id] = c;
return a;
},{})
}
There are other ways you could do this using things like Array.prototype.find()
or nested loops that might shorten the code but be slightly less efficient in the long run than creating hashmap objects
Upvotes: 1
Reputation: 68933
Try the following:
var array1 = [{ "id": 1, "name": "potatoe", "photo":"photo"}, {"id": 2, "name": "budget"}];
var array2 = [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name":
"UhOhAnotherName"}, {"id": 2, "name": "budget"}];
array1.map(function(val,i){
array2.forEach(function(v){
if(val.id == v.id){
val.name = v.name;
}
else{
var found = array1.some(function (el) {
return el.id === v.id;
});
if (!found) { array1.push(v); }
}
})
return val;
});
console.log(array1);
Upvotes: 1