比较两个Google Apps Script中的字典。

huangapple go评论58阅读模式
英文:

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"
}

huangapple
  • 本文由 发表于 2023年1月9日 16:56:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定