0

I have an object which contains an array of objects like

{ 
    0: [
          { value:1}
          { value:2}
          { value:3}

       ]
}

I am trying to check if an element is inside the array, so what i'm doing i'm looping over it like Object.values(object).some(el => el.value === someNumber) but it always returns false, anyone has any ideea why? someNumber can be anything, it's a dynamic value.

3 Answers 3

2

You try to check el that is actualy array with someNumber, that I supposed is number. To do what you whant you need to smth like this:

const obj = { 
  0: [
    { value:1},
    { value:2},
    { value:3}
 ]
}

const someNumber = 2;
const result = Object.values(obj).some((arr) => arr.some((el) => el.value === someNumber));
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

2

You need another level, because Object.values returns an array of an array.

var object = { 0: [{ value: 1 }, { value: 2 }, { value: 3 }] };

console.log(Object.values(object).some(values => values.some(el => el.value === 2)));
console.log(Object.values(object).some(values => values.some(el => el.value === 7)));

1 Comment

You made a mistake : values => some should be values => values.some
2

The array is in the [0] element of the object, so you should use object[0], not Object.values(object).

const object = { 
  0: [
    { value:1},
    { value:2},
    { value:3}
 ]
}

console.log(object[0].some(el => el.value === 1));
console.log(object[0].some(el => el.value === 6));

Unless your object can contain more properties and you want to search all of them. Then the other answers are more correct.

Comments

Your Answer

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.