I have the following object:
{
apple: 0,
banana: 0,
cherry: 0,
date: 0,
and so on...
}
And an array of strings that are words from a cookery book.
[0] => "the"
[1] => "apple"
[2] => "and"
[3] => "cherry"
and so on...
I would like to iterate over the array of strings and add +1 every time the above keys are mentioned as a string? I've been trying to use object.keys however have been unable to get it working?
This is in node.js.
3 Answers 3
You can do something nice and simple like this, which will increment absolutely all keys from the array of strings:
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)
However, if you want to only increment keys in the ingredients
object that you set, you can do this:
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)
-
The ingredients object and the array of words from the book are both in their own respective files within a function each. I have them logging to the console currently, how can I include them within what you have entered above. Is it as easy as making a new file using module exports and then assigning their function let ingredients() = ingredients?TheApp– TheApp2020年04月15日 09:21:40 +00:00Commented Apr 15, 2020 at 9:21
You can simplify it using 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);
Another way to handle it using array filter
and some
:
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);