Replace Array Of Object With Another Array Of Object Base On Property
How to replace array of object with another array of object base on property? var arr = [ {'status':'ok'}, {'status':'ok'}, {'status':'error'} ] var arr2 = [ {'sta
Solution 1:
You can do it using Array#map()
to create a new array and Array#find()
to find the object in the second array
let arr=[{status:"ok"},{status:"ok"},{status:"error"}],
arr2=[{status:"error",msg:"etc","more property":!0}];
arr = arr.map(a=>{
let fullObj = arr2.find(a2=>a2.status===a.status);
return fullObj ? fullObj : a;
});
console.log(arr);
Solution 2:
You could use Object.assign
for assigning new properties to a given object.
var arr = [{ status: 'ok' }, { status: 'ok' }, { status: 'error' }],
arr2 = [{ status: 'error', msg: 'etc', 'more property': true }];
arr.forEach(obj => {
if (obj.status === 'error') {
Object.assign(obj, arr2[0]);
}
});
console.log(arr);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 3:
var arr = [
{'status':'ok'},
{'status':'ok'},
{'status':'error'}
]
var arr2 = [
{'status':error, 'msg': 'etc', 'more property':true}
]
arr = arr.forEach(obj => { if(obj.status === 'error'){obj = arr2[i]} return obj })
The callback in forEach() can take an additional arg for the index, but you forgot to provide it. So if you're trying to access the index you can do that.
Also, you're assigning arr to the output of forEach, but forEach() does not return anything, it just executes a callback for every element in the array. What you can do is swap it out for map, which is similar, but actually returns a new array.
Ex:
arr = arr.map((obj, i) => obj.status === 'error' ? arr2[i] : obj)
Solution 4:
I think what you're trying to do is replace the one with status "error" to be the arr2 object [0] so..
for(obj in arr){
arr[obj] = arr[obj]['status'] == 'error' ? arr2[0] : arr[obj];
}
Post a Comment for "Replace Array Of Object With Another Array Of Object Base On Property"