to copy the values from one dictionary to other dictionary in javascript

Viewed 26298

The following code snippet is unable to copy the contents from one dictionary to other. It is throwing a type error showing "copy.Add is not a function". Can someone suggest the ways to copy the key-value pairs from one dictionary to other.

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict);
for(var key in dict)
{
   copy.Add(key, dict[key]);
}
console.log(copy);
3 Answers

In Javascript, use Object.assign(copy, dict) to copy contents into another already existing dictionary (i.e. "in-place" copy):

dict = {"Name":"xyz", "3": "39"};
var copy={};
console.log(dict, copy);
Object.assign(copy, dict);
console.log(dict, copy);

In newer JavaScript versions, you can also clone a dict into a new one using the ... operator (this method creates a new instance):

var copy = {...dict};

Extra: You can also combine (merge) two dictionaries using this syntax. Either in-place:

Object.assign(copy, dict1, dict2);

or by creating a new instance:,

var copy = {...dict1, ...dict2};
Related