2

I have a javascript object on a page that contains some info. I need to loop through the object and copy it to another object.

Here is my starting code

var p_tag = {};
var new_tag = {};
p_tag.abc='abc';
p_tag.def='def';
p_tag.ghi='ghi';

for (var key in p_tag) {
   if (p_tag.hasOwnProperty(key)) {
   console.log(key + "'s favorite fruit is " + p_tag[key]);
   }
}

I need to take the values from p_tag and copy them to new_tag as another object.

I may not know what keys are available on each page so looking for something that can go through all available p_tags and copy them to new_tag.

Thanks,

gteh
  • 741
  • 10
  • 17
  • You can skip the `if (p_tag.hasOwnProperty(key))`. That's like "for each key in this object, check if this object has that key". Just assign it to `new_tag` – Pimmol Apr 06 '16 at 14:15

2 Answers2

6

The easiest way to do a deep copy of an object:

var copy = JSON.parse(JSON.stringify(obj));

So it basically turns your object into a string and then back into an object again with zero references to the original.

shashanka n
  • 2,568
  • 1
  • 14
  • 21
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • Thank you. This looks simple enough. Any drawbacks to it vs using what Luka posted below which uses the for loop? – gteh Apr 06 '16 at 14:16
  • Yes. if any of those sub items are objects also objects themselves they will still be referenced in Lukas version, in mine all of the references will be broken. – Naftali Apr 06 '16 at 14:16
3

Just assign all of the old values to the new values.

for (var key in p_tag) {
   if (p_tag.hasOwnProperty(key)) {
       console.log(key + "'s favorite fruit is " + p_tag[key]);

       new_tag[key] = p_tag[key];
   }
}
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57