Evanss
Evanss

Reputation: 23173

Trouble testing some twice with JavaScript

I have an object with 2 items, each item contains an array of numbers.

selected: {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}

In a function I need to do something if the number passed to it isn't in either item. So for instance if 6 is passed do nothing, but if 7 is passed then do something.

The following returns true and false if one of the items contains the number

Object.entries(selected).forEach((itemParent)=>{
  console.log(
    itemParent[1].some((itemChild)=>{
      return itemChild === no;
    })
  )
});

But when I add the code below I get an error: Uncaught TypeError: Cannot read property 'some' of undefined

Object.entries(selected)
  .forEach((itemParent)=>{
    itemParent[1].some((itemChild)=>{
      return itemChild === no;
    })
  }
).some((item)=>{
  return item === true;
});

Im using bable so I can use the latest ES6 syntax.

Upvotes: 0

Views: 58

Answers (5)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

You can use Object.values in combination with concat function in order to obtain a more simple approach.

let selected= {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
};
let contains= [].concat(...Object.values(selected)).includes(7);
console.log(contains);

Upvotes: 1

Faly
Faly

Reputation: 13356

A simpler approach I think:

var selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}
function exists(inputNumber) {
    return Object.keys(selected).some(key => selected[key].some(number => number === inputNumber));
}
console.log(exists(6));
console.log(exists(7));

And even simpler with Object.values:

var selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
}
function exists(inputNumber) {
    return Object.values(selected).some(arr => arr.some(number => number === inputNumber));
}
console.log(exists(6));
console.log(exists(7));

Upvotes: 0

str
str

Reputation: 45019

You are overcomplicating things. And btw, you are even using ES2017 features, so check whether Babel is configured accordingly.

Here is a short solution to your problem:

const no = 7;

const selected = {
  item1: [1, 2, 3],
  item2: [4, 5, 6]
};

const containsNumber = Object.values(selected).some(array => array.includes(no));

console.log(containsNumber);

The reason you got an error message was that forEach does not actually return anything.

Upvotes: 2

Serge K.
Serge K.

Reputation: 5323

You're getting this error in your second example because forEach doesn't return the array but undefined, and undefined doesn't have any method named some.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386848

Assuming the object is different than the given data, then you could nest some and check. Then return the result of checking.

return Object
    .entries(selected)
    .some(itemParent => itemParent[1].some(itemChild => itemChild === no))

Upvotes: 2

Related Questions