2

I have a very simple javascript hash (object that is only properties):

var original_color = {
  r: 214,
  g: 124,
  b: 55
};

I want to copy the entire hash and then alter it:

var new_color = original_color;
new_color.r = 50;

Does javascript have any built in way to copy dictionaries? Or is there some other JS data type I'm supposed to be using for working with hashes / dictionaries?

There's a related question on SO about cloning objects: How do I correctly clone a JavaScript object?. But I'm surprised there is no easy way to simply copy a hash, or essentially an object that only has properties and no methods, prototype, etc.

Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432
  • Use an extend(), Object.create(), or a JSON sandwich if you have object sub-objects. – dandavis Oct 02 '14 at 22:26
  • Nope, there's no primitive mechanism in the language to do that. – Pointy Oct 02 '14 at 22:27
  • The clone answer in that answer is what you would do. There isn't a difference between objects and hashes in js. You need to iterate over object A and add those to object B. – scrappedcola Oct 02 '14 at 22:30
  • We don't call them "hashes" in JavaScript. This is an Object, plain and simple. I don't see what else you think it could contain beyond properties. Consequently I don't see why the existing solution you link to is not good enough for you? – Lightness Races in Orbit Oct 02 '14 at 22:41

2 Answers2

4

You can use Object.assign

var original_color = {
r: 214,
g: 124,
b: 55
};   
var new_color = Object.assign({},original_color)
0

Well, this will do the trick, but it is not elegant, just a stripped down version on a an answer you referenced before.

var original_color = {
r: 214,
g: 124,
b: 55
};   
var new_color ={};    
for (prop in original_color){
  if (original_color.hasOwnProperty(prop)){
    new_color[prop] = original_color[prop];
 }
}
new_color.r = 50;
Beckafly
  • 411
  • 2
  • 5