簡體   English   中英

如何在JavaScript中從另一個字典的鍵更改字典的鍵?

[英]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); 

你可以這樣做:

  1. 迭代第一個對象(dict1)並創建一個新對象,讓我們說一下鍵和值被反轉的臨時值。 所以臨時看起來像{Alex:Name,61:3}。
  2. 迭代dict2並在鍵“undefined”處獲取值(在這種情況下為61),然后從反轉對象中讀取值得到3.將其用作鍵(3)並放置值(61)。
  3. 從dict2中刪除鍵“undefined”。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM