If I have an object:
var array = [];
var theobject = null;
array.push({song:"The Song", artist:"The Artist"}, {song:"Another Song", artist:"Another Artist"});
and I do:
for(var i = 0; i < array.length; i++)
if(array[i].song == "The Song") {
theobject = array[i];
break;
}
If I then change theobject by doing:
theobject.song = "Changed Name";
I am having problems where despite myself trying to set ONLY “theobject.song” to be equal to “Changed Name”, array[0].song becomes set to “Changed Name” also.
What I want is “theobject.song” to become “Changed Name” while array[0].song remains “The Song”.
What is the best way to accomplish this?
You will never get a reference to your object in the loop. Try:
That will give a reference to the object, and you will be able to change the objects
songproperty.If you want to use a copy of the object, then you’ll have to do a manual copy. E.g.
And your loop becomes: