开发者

JavaScript: How to efficiently replace all values of an object without replacing the object

开发者 https://www.devze.com 2023-01-06 05:51 出处:网络
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 w

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 effic开发者_如何学Goient 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];
}


You could use the handle/body pattern, so the objects in the array only have a single property, which has all the real properties for the object:

var values = [{values:{id:1, name:'Bob'}}, {values:{id:2, name:'Alice'}}, {values:{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].values = newValue; // set the values of the object, not the object
console.info(bar === values[2]); // Still true


I'd advise you to replace the objects attached to DOM elements at the same time that you replace the objects in your array. That way, the comparison still holds true.

If that's not possible, then in your example we can see that you only really replace the name property. So you just have to copy the name property from the Ajax object to the Array object.

0

精彩评论

暂无评论...
验证码 换一张
取 消