JavaScript: how to effectively replace all values ​​of an object without replacing an object

I have a number of objects collected in an array. The same objects are also tied to some 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 an object in the array with the same id property as the one that received the new values ​​through AJAX, and then replace it. But this, of course, creates a new object, and the objects attached to the DOM elements no longer match. This means that if I compared them, they would not be the same object anymore.

How can I easily replace the correct object with the values ​​in the new object without replacing the actual object? (So ​​the link remains the same)

An example of what I do not 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 

The only way I can think of is to iterate over the object using foreach or something like that, but hoping there is something built into javascript or jQuery or something that allows you to use a more efficient or at least least cleaner code.

+4
source share
3 answers

You can iterate over the values ​​of the new and set them in the old:

 for (i in newValue) { oldValue[i] = newValue[i]; } 
+6
source

You can use the handle / body template, so the objects in the array have only one property that 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 
+2
source

I would advise you to replace the objects attached to the DOM elements, while replacing the objects in your array. Thus, the comparison is still preserved.

If this is not possible, then in your example we will see that you really replace the name property. So you just need to copy the name property from the Ajax object to the Array object.

+1
source

Source: https://habr.com/ru/post/1315035/


All Articles