In Javascript, How To Conditionally Update A Property Of An Object?
Solution 1:
In a comment you've said:
I will only update properties that exist in the old object, new properties that don't exist in the old object will not be added.
That means we have to leave spread syntax and Object.assign
out of the picture, as both of them would copy all properties from newObj
over to oldObj
.
Instead, we can use a simple loop (and if this comes up a lot, you can create a function, perhaps updateObject
):
for (const key ofObject.keys(newObj)) {
if (key in oldObj) {
oldObj[key] = newObj[key];
}
}
let oldObj = {test1: 'valueTest1',test2: 'valueTest2',test3: 'valueTest3' };
let newObj = {test2: 'newValue2', xyz: "don't copy me"};
for (const key ofObject.keys(newObj)) {
if (key in oldObj) {
oldObj[key] = newObj[key];
}
}
console.log(oldObj);
(You may prefer oldObj.hasOwnProperty(key)
instead of key in oldObj
, depending on your rules for updating.)
Or using the relatively-new Object.entries
and some destructuring:
for (const [key, value] ofObject.entries(newObj)) {
if (key in oldObj) {
oldObj[key] = value;
}
}
let oldObj = {test1: 'valueTest1',test2: 'valueTest2',test3: 'valueTest3' };
let newObj = {test2: 'newValue2', xyz: "don't copy me"};
for (const [key, value] ofObject.entries(newObj)) {
if (key in oldObj) {
oldObj[key] = value;
}
}
console.log(oldObj);
Before the clarification quoted above, I'd posted the following about spread and Object.assign
. Just for completeness, but they don't apply to your case where you want to skip properties that oldObj
doesn't have:
You don't have to be anything like that complicated with the spread syntax, just:
oldObj = {...oldObj, ...newObj};
let oldObj = {test1: 'valueTest1',test2: 'valueTest2',test3: 'valueTest3' };
let newObj = {test2: 'newValue2', xyz: "I get copied too"};
oldObj = {...oldObj, ...newObj};
console.log(oldObj);
That will create a new object with all of oldObj
's and newObj
's properties, with newObj
's properties winning if both have the same name.
Note that property spread is brand-new, just approved to Stage 4 (will be in the ES2018 spec). If you don't want to use a Stage 4 proposal, use Object.assign
:
oldObj = Object.assign({}, oldObj, newObj);
let oldObj = {test1: 'valueTest1',test2: 'valueTest2',test3: 'valueTest3' };
let newObj = {test2: 'newValue2', xyz: "I get copied too"};
oldObj = Object.assign({}, oldObj, newObj);
console.log(oldObj);
You'd also use Object.assign
if you want to update oldObj
in-place instead of creating a new object:
Object.assign(oldObj, newObj);
let oldObj = {test1: 'valueTest1',test2: 'valueTest2',test3: 'valueTest3' };
let newObj = {test2: 'newValue2', xyz: "I get copied too"};
Object.assign(oldObj, newObj);
console.log(oldObj);
Post a Comment for "In Javascript, How To Conditionally Update A Property Of An Object?"