检查字符串数组是否包含对象键

时间:2020-04-14 21:16:49

标签: arrays node.js object

我有以下对象:

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

and so on...
}

还有一串字符串,它们是烹饪书中的单词。

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

以此类推...

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

这是在node.js中。

3 个答案:

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

答案 1 :(得分:0)

使用数组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);

答案 2 :(得分:0)

您可以使用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);