2017-05-14 61 views
1

我有一本字典dict1:{Name:"Alex", 3: "61"}。我創建了一個包含相同鍵值對的副本字典dict2。然後我將dict2作爲參數發送給一個函數,然後轉換爲這些值:dict2={1: "Alex",undefined: "61"}如何從JavaScript中的另一個字典的鍵更改字典的鍵?

有人可以幫我編寫代碼來代替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"}; 

回答

0

獲取和存儲的財產"undefined"值,delete"undefined"財產;迭代屬性,值爲dict1,如果屬性值與存儲值匹配,則將屬性設置爲dict2,將屬性名稱匹配爲dict1將存儲變量設置爲set屬性的值。

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

+0

是這方面的工作? – Kenz

+0

該方法返回OP中描述的預期結果。你也可以使用'JSON.stringify()','.replace()''JSON.parse(JSON.stringify(dict2).replace(/ undefined /,3))' – guest271314

0

你可以這樣做:

  1. 遍歷第一目標(dict1),並創建一個新的對象,可以說temp其中鍵和值是顛倒的。所以臨時看起來像{Alex:Name,61:3}。
  2. 迭代dict2並在「未定義」鍵處獲取值(本例中爲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);

+0

...這段代碼工作正常只有一個未定義的值。當我嘗試使用這本詞典時,var dict2 = {0121}1:「Alex」, undefined:「61」, undefined:「London」 }; ,以下代碼失敗 – Kenz

+0

var dict1 = {1:「Alex」,年齡:「61」,家庭:「倫敦」}; var dict2 = {1:「Alex」,undefined:「61」,undefined:「London」};以下代碼不起作用。你能修好它嗎? – Kenz

+0

@Kenz在JavaScript中,對象只能有一個鍵。在你的情況下,你有兩個地方沒有定義爲關鍵。第二個會覆蓋第一個。因此,你的'dict2'看起來像{1:「Alex」,undefined:「London」},換句話說,你的對象只能有一個未定義的鍵, 。 –

相關問題