[英]How to change the keys of a dictionary from keys of another dictionary in JavaScript?
我有一個字典dict1:{Name:"Alex", 3: "61"}
。 我創建了一個重復的字典dict2
其中包含相同的鍵值對。 然后我將dict2作為參數發送給一個函數,然后轉換為這些值: dict2={1: "Alex",undefined: "61"}
。
有人可以幫我編寫替換undefined:61
代碼到原始字典中的代碼嗎? 最終的決定必須是: dict={1: "Alex",3: "61"};
dict1={Name:"Alex", 3: "61"};
dict2={Name:"Alex", 3: "61"}; //created a copy of original dictionary
function(dict2){
//some function that converts dict2 to the following value.
}
console.log(dict2); //dict2={1: "Alex",undefined: "61"}
//now i want to write the code to substitute the undefined key-value pair to the one present in the original.
//my final dict has to be as follows:
dict={1: "Alex",3: "61"};
獲取並存儲屬性"undefined"
的值, delete
"undefined"
屬性; 迭代性能,值dict1
,如果存儲值屬性匹配,在設置屬性的值dict2
以匹配屬性名dict1
組存儲的變量來設置屬性的值。
dict1 = { Name: "Alex", 3: "61" }; dict2 = { 1: "Alex", undefined: "61" }; let {undefined:val} = dict2; delete dict2["undefined"]; for (let [key, prop] of Object.entries(dict1)) { if (prop === val) dict2[key] = val; } console.log(dict2);
你可以這樣做:
var dict1 = { Name: "Alex", 3: "61" }; var dict2 = { 1: "Alex", undefined: "61" }; var temp = {}; for (var i in dict1) { temp[dict1[i]] = i; } for (var key in dict2) { if (key == "undefined") { var val = dict2[key]; dict2[temp[val]] = val; } } delete dict2["undefined"]; console.log(dict2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.