1

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.

asked Apr 14, 2020 at 21:16

3 Answers 3

1

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)

answered Apr 14, 2020 at 21:24
1
  • 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? Commented Apr 15, 2020 at 9:21
0

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);

answered Apr 14, 2020 at 21:40
0

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);

answered Apr 14, 2020 at 21:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.