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);
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};
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With