【问题标题】:Checking if Array of strings contains Object keys检查字符串数组是否包含对象键
【发布时间】:2020-07-27 18:04:57
【问题描述】:

我有以下对象:

{
  apple: 0,
  banana: 0,
  cherry: 0,
  date: 0,

and so on...
}

还有一组来自烹饪书的字符串。

[0] => "the"
[1] => "apple"
[2] => "and"
[3] => "cherry"

等等……

我想遍历字符串数组并在每次将上述键作为字符串提及时添加 +1?我一直在尝试使用 object.keys 但无法使其正常工作?

这是在 node.js 中。

【问题讨论】:

    标签: arrays node.js object


    【解决方案1】:

    您可以像这样简单而简单地做一些事情,这将绝对递增字符串数组中的所有键:

    let ingredients = {
      apple: 0,
      banana: 0,
      cherry: 0,
      date: 0,
      // and more...
    }
    
    let arr = ["the","apple","and","cherry"]
    
    // loop through array, incrementing keys found
    arr.forEach((ingredient) => {
      if (ingredients[ingredient]) ingredients[ingredient] += 1;
      else ingredients[ingredient] = 1
    })
    
    console.log(ingredients)

    但是,如果您想只增加您设置的ingredients 对象中的键,您可以这样做:

    let ingredients = {
      apple: 0,
      banana: 0,
      cherry: 0,
      date: 0,
      // and more...
    }
    
    let arr = ["the","apple","and","cherry"]
    
    // loop through array, incrementing keys found
    arr.forEach((ingredient) => {
      if (ingredients[ingredient] !== undefined)
        ingredients[ingredient] += 1;
    })
    
    console.log(ingredients)

    【讨论】:

    • 书中的成分对象和单词数组都在一个函数中各自的文件中。我目前让他们登录到控制台,我怎样才能将它们包含在您上面输入的内容中。是否像使用模块导出创建一个新文件然后分配它们的函数一样简单?
    【解决方案2】:

    使用数组filtersome 处理它的另一种方法:

    var fruits = {
      apple: 0,
      banana: 0,
      cherry: 0,
      date: 0,
    };
    
    const words = ["the", "apple", "and", "cherry"];
    
    var filtered = words.filter(word => Object.keys(fruits).includes(word));
    filtered.forEach(fruit => fruits[fruit] += 1);
    
    // fruits
    // {apple: 1, banana: 0, cherry: 1, date: 0}
    console.log(fruits);

    【讨论】:

      【解决方案3】:

      您可以使用reduce 来简化它。

      const words = ["the", "apple", "and", "cherry"];
      
      let conts = {
        apple: 0,
        banana: 0,
        cherry: 0,
        date: 0,
      };
      const result = words.reduce((map, word) => {
        if (typeof map[word] !== "undefined") map[word] += 1;
        return map;
      }, conts);
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 2019-10-01
        • 2022-06-30
        • 2021-12-14
        • 2020-08-11
        相关资源
        最近更新 更多