Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 449
Kenz Avatar asked May 14 '17 11:05

Kenz


2 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};
like image 145
Sohail Si Avatar answered Oct 30 '22 12:10

Sohail Si


You won´t need to call add on the copy-variable`. You can directly use the indexer as follows:

dict = {"Name":"xyz", "3": "39"};
var copy = {};
console.log(dict);
for(var key in dict)
{
    copy[key] = dict[key];
}
console.log(copy);
like image 35
MakePeaceGreatAgain Avatar answered Oct 30 '22 11:10

MakePeaceGreatAgain