如何在JavaScript中从另一个字典的键更改字典的键?

时间:2017-05-14 15:26:36

标签: javascript dictionary

我有一本字典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"};

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你可以这样做:

  1. 迭代第一个对象(dict1)并创建一个新对象,让我们说一下临时键和值的反转。所以临时看起来像{Alex:Name,61:3}。
  2. 迭代dict2并在键#34; undefined",得到值(在这种情况下为61),然后从反转对象中读取值得到3.使用它作为键(3)并放值(61)。
  3. 删除密钥" undefined"来自dict2。
  4. 
    
    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);