Javascript object reference associated with an object in an array?

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:

for(var i = 0; i < array.length; i++)
if(array[i].song == "The Song") {
theobject = array[i];
break;
}

If I then changed the object by doing:

theobject.song = "Changed Name";

I am having problems when, even though I am trying to set ONLY "theobject.song" to "Changed Name", the array [0] .song is also set to "Changed Name".

I want "theobject.song" to become "Changed Name", while array [0] .song remains "Song".

What is the best way to do this?

+3
source share
2 answers

You will never get a link to your object in a loop. Try:

for(var i = 0; i < array.length; i++)
 if(array[i].song === "The Song") {
 theobject = array[i];
 break;
}

This will give a reference to the object and you can change the property of the objects song.

, . .

function clone(obj) {
  var copy = {};
  for (var attr in obj) {
   if (obj.hasOwnProperty(attr)) {
     copy[attr] = obj[attr];
   }
  }
  return copy;
}

:

for(var i = 0; i < array.length; i++)
 if(array[i].song === "The Song") {
 theobject = clone(array[i]);
 break;
}
+7

Object.assign() .

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

var array = [];
var theobject = null;

array.push({
  song:"The Song", 
  artist:"The Artist"
  }, 
  {
  song:"Another Song", 
  artist:"Another Artist"
});

for(var i = 0; i < array.length; i++)
  if(array[i].song == "The Song") {
    theobject = Object.assign( {}, array[i] );
    break;
  }
  
theobject.song = "Changed Name";

console.log( array );
console.log( theobject );
Hide result
+1

All Articles