Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object reference linked to object in array?

Tags:

javascript

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?

like image 440
Rolando Avatar asked May 09 '12 04:05

Rolando


2 Answers

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

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

That will give a reference to the object, and you will be able to change the objects song property.

If you want to use a copy of the object, then you'll have to do a manual copy. E.g.

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

And your loop becomes:

for(var i = 0; i < array.length; i++)
 if(array[i].song === "The Song") {
 theobject = clone(array[i]);
 break;
}
like image 146
KooiInc Avatar answered Nov 15 '22 17:11

KooiInc


It possible to use Object.assign() to only copy its value without the reference.

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 );
like image 37
Tarik Chakur Avatar answered Nov 15 '22 16:11

Tarik Chakur