英文:
compare two dictionaries in google apps script
问题
我有两个字典
old = { C43: 'X13',
C59: 'X13',
C75: 'X14',
C91: 'X14',
C107: 'X16',
C123: 'X17' }
new = { C139: 'X17' }
我尝试匹配两个字典的值,并将old
中与new
匹配的keys
移动到一个新数组中。
输出结果应该是一个新数组,如下所示:
new_array = [ C123 ]
我尝试了以下方法,但是似乎不正确,请指导:
var new_array = [];
for (var key in old) {
var check_matching_value = old[key] === new[key];
if (check_matching_value == true) {
new_array.push(key);
}
}
console.log(new_array);
英文:
I have two dictionaries
old = { C43: 'X13',
C59: 'X13',
C75: 'X14',
C91: 'X14',
C107: 'X16',
C123: 'X17' }
The ```old`` can have any number of entries.
and
new = { C139: 'X17' }
The ```new`` can have any number of entries.
I am trying to match the values of both dictionaries and move the keys
from old
wherever the values in old
and new
match.
The output to be in a new array as,
new_array = [ C123 ]
I tried the below, but I am not doing it right, Please guide
var new_array = [];
for (var key in old) {
var check_matching_value = old[key] === new[key]
if (check_matching_value == true) {
new_array.push(key);
}
}
console.log(matchingKeys);
答案1
得分: 1
使用 Array.filter()
,像这样:
function test() {
const oldDict = {
C43: 'X13',
C59: 'X13',
C75: 'X14',
C91: 'X14',
C107: 'X16',
C123: 'X17',
};
const newDict = { C139: 'X17', };
const newValues = Object.values(newDict);
const newArray = Object.keys(oldDict)
.filter(key => newValues.includes(oldDict[key]));
console.log(newArray); // "C123"
}
英文:
Use Array.filter()
, like this:
function test() {
const oldDict = {
C43: 'X13',
C59: 'X13',
C75: 'X14',
C91: 'X14',
C107: 'X16',
C123: 'X17',
};
const newDict = { C139: 'X17', };
const newValues = Object.values(newDict);
const newArray = Object.keys(oldDict)
.filter(key => newValues.includes(oldDict[key]));
console.log(newArray); // "C123"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论