I have a number of objects collected in an array. The same objects are also attached to certain DOM elements for various reasons. From time to time I need to update one of these objects. The easiest way to do this is to find the object in the array with the same id property as the one I got new values for through AJAX and then replace it. But this of course creates a new object and the objects attached to DOM elements are no longer the same. Which means that if I would compare them they would not be the same object anymore.
How can I easiest replace the correct object with the values in the new object without replacing the actual object? (So that the reference remains the same)
Example of what I don't want
var values = [{id:1, name:'Bob'}, {id:2, name:'Alice'}, {id:3, name:'Charlie'}];
var bar = values[2];
console.info(bar === values[0]); // True
var newValue = {id:1, name:'Dave'};
// Somehow find the index of the object with id==3
values[2] = newValue;
console.info(bar === values[2]); // False, should still be true
Only way I can think of is looping through the object with a foreach or something, but hoping there is something built-in to javascript or jQuery or something that allows for more efficient or at least cleaner code.
You can iterate the values of the new one and set them in the old one:
for (i in newValue) {
oldValue[i] = newValue[i];
}
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