Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

search for a specific property in array of objects and return boolean

lets say i have an array of objects

    let arr = [
  {
    name: "john",
    age: 22
  },
  {
    name: "george",
    age: 55
  }
];

and an object

  let obj = {
    name: "bill",
    age: 55
  }

and i want to search all arr objects to find anyone with the same age as obj.age and return a boolean depending whether it includes a same property or not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i can obviously do :

let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;

but is there a way to call a method (lodash,plain js or whatever) to just get this by design like method(arr,obj.age) //returns true ?

let arr = [
  {
    name: "john",
    age: 22
  },
  {
    name: "george",
    age: 55
  }
];

let obj = {
  name: "bill",
  age: 55
}

let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;

console.log(bool)

>Solution :

You can use some. So basically it will return a boolean value if any of the object property in array matches the required value

let arr = [{
    name: "john",
    age: 22
  },
  {
    name: "george",
    age: 55
  }
];
let obj = {
  name: "bill",
  age: 55
}

const val = arr.some(item => item.age === obj.age);
console.log(val)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading