我有一本字典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"};
答案 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)
你可以这样做:
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);