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

Posted in :

javascript 裡的 dict 遇到等號時, 2個物件會是 assign by address, 所以內容會互相影像,


// "Spread"
{ ...dict }

// "Object.assign"
Object.assign({}, dict )

// "JSON"
JSON.parse(JSON.stringify(dict ))


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};


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *