TheApp
TheApp

Reputation: 47

Checking if Array of strings contains Object keys

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.

Upvotes: 1

Views: 1106

Answers (3)

Chris Diana
Chris Diana

Reputation: 15

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

Upvotes: 0

xdeepakv
xdeepakv

Reputation: 8125

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

Upvotes: 0

Blundering Philosopher
Blundering Philosopher

Reputation: 6805

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)

Upvotes: 1

Related Questions