I want to update an object that could look like this:
currentObject = { someValue : "value", myObject : { attribute1 : "foo", attribute2 : "bar" } };
.. with an object that contains some changes i.e.:
updateObject = { myObject : { attribute2 : "hello world" } };
At the end I would like to have currentObject updated so that:
currentObject.myObject.attribute2 == "hello world"
That should be posible for other objects as well.. As a solution I thought about iterating over the object and somehow take care of the namespace. But I wonder if there is an easy solution for that problem by using a library like jQuery or prototype.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.
var clone = Object. assign({}, obj); The Object. assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
Updating Object Properties After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update. For example, let's look at ourDog:
Update JavaScript object with another object, but only existing keys? For this, use hasOwnProperty (). Following is the code − To run the above program, you need to use the following command −
JavaScript offers two ways to update the object, using map () and findIndex (). This built-in array method, provided by JavaScript, iterates over the original array and creates the new array, completing the elements based on the specified conditions. Instead of an arrow function, you can also pass the callback function.
Think about what it does. It takes one of the references to an object and then it uses that reference to get access to the actual value stored inside of that object. And then it updates the existing value with a new value - "Updated value". In other words - it mutates the original object that we've declared at the very beginning of our code.
I suggest using underscore.js (or better, lo-dash) extend:
_.extend(destination, *sources)
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.
_.extend({name: 'moe'}, {age: 50}); => {name: 'moe', age: 50}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With