Вы можете сделать что-то хорошее и простое, как это, которое будет увеличивать абсолютно все ключи из массива строк:
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)