EDIT: Thanks 4 all the great, diverse answers - I chose the solution that worked for me even after I realized that I needed more requirements: I also needed new properties to be added and for it to work with arrays in objects as well.
Here's what I wanna do: Update one object through another one.
Here are some constraints:
- Only properties that the new object has should be updated (and that the original object also has), the other properties should remain unchanged, NOT DELETED
- Nested objects should also be updated in the same way
My Problem is that I don't know how to easily do this for nested objects because typeof x === "object" also returns true for Date objects for example.
Here's what I got so far:
let originalObj = {
dateCreated: new Date(2021, 1, 10),
value: "100",
subObj: {
count: 55,
val: null
}
};
let updateObj = {
dateCreated: new Date(2021, 1, 11),
subObj: {
val: 90
}
};
let updateOrignal = (oObj, uObj) => {
for (let prop in uObj) {
if (uObj.hasOwnProperty(prop) &&
oObj.hasOwnProperty(prop)) {
oObj[prop] = uObj[prop];
}
}
};
console.log(originalObj);
updateOrignal(originalObj, updateObj)
console.log(originalObj);
Currently my updated object looks like this:
{
"dateCreated": "2021-02-10T23:00:00.000Z",
"value": "100",
"subObj": {
"val": 90
}
}
My goal:
{
"dateCreated": "2021-02-10T23:00:00.000Z",
"value": "100",
"subObj": {
"count": 55,
"val": 90
}
}
updateObj.hasOwnProperty(prop)<= should useuObj. Probably not the issue, but it is inconsistent.