Home > Blockchain >  How can I use .some() to find if an array of objects contains a specific property value
How can I use .some() to find if an array of objects contains a specific property value

Time:09-23

I've an array containing objects, where every object represents a person that's going to a video theatre. The objects contains properties such as Name, Age and Hobby. If there is (atleast) one person younger than 18, the variable censor should be set to true.

My code below yields the value false, despite Tim being younger than 18. Is it not possible to use .some() this way, or what am I doing wrong?

var persons = [
    {Name: "Joel", Age:25, Hobby:"Fishing"},
    {Name: "Michael", Age:31, Hobby:"Astronomy"},
    {Name: "Tim", Age:12, Hobby:"Video Games"},
]

var censor = persons.some((person) => {person.Age < 18})
console.log(censor) --> false

CodePudding user response:

It's

var censor = persons.some((person) => person.Age < 18); // <-- no curly brackets for the predicate

instead of {person.Age < 18}

CodePudding user response:

You need to remove the brackets.

var persons = [
    {Name: "Joel", Age:25, Hobby:"Fishing"},
    {Name: "Michael", Age:31, Hobby:"Astronomy"},
    {Name: "Tim", Age:12, Hobby:"Video Games"},
]

var censor = persons.some((person) => person.Age < 18)
console.log(censor)

If you want to continue using brackets, then you need to add return to the statement:

var censor = persons.some((person) => {
  return person.Age < 18
})

CodePudding user response:

You are missing a return in your callback that is why it is always false,

either use:

var censor = persons.some(person => person.Age < 18)

or

var censor = persons.some(person => {return person.Age < 18 })
  • Related