According to this problem, Object.assign()
is more suitable to solve this problem. One by one value assignment creates many boilerplate, needs more effort.
The Object.assign()
method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.
Code block:
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
var obj = {
id: 3,
online: true
}
function mergeObjByID(item) {
if (item.id === obj.id){
//overwrite item value
Object.assign(item,obj)
return true
}
}
const result = arr.filter(mergeObjByID);
console.log(result)
More about Object.assign() example:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }