Jim
Jim

Reputation: 53

Searching object in object array

I have the following array:

const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];

I'm trying to pass another object { id: 5, squad: 'Justice League' } into the array to find the matching object.

for example:

findOne(HEROES, { id: 5, squad: 'Justice League' }) 

should return

{ id: 5, name: 'Wonder Woman', squad: 'Justice League' }

I'm not sure how to start this, any help would be appreciated.

Upvotes: 0

Views: 67

Answers (3)

Jack Bashford
Jack Bashford

Reputation: 44087

Use find:

const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];

const findOne = (arr, query) => {
  const { id, squad } = query;
  return arr.find(({ id: a, squad: b }) => (id != undefined ? a == id : true) && (b != undefined ? b == squad : true));
};

console.log(findOne(HEROES, { id: 5, squad: "Justice League" }));

Upvotes: 3

Liang
Liang

Reputation: 515

Similar Code using find

const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];

const findOne=(arr,obj)=>arr.find(x=>x.id==obj.id&&x.squad==obj.squad);

console.log(findOne(HEROES, { id: 7, squad: 'Avengers' }));

Upvotes: 0

thinice
thinice

Reputation: 710

Have a look at a utility library like underscore JS or Lodash. They have just such functionality for that.

From lodash docs:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'

// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'

Upvotes: 0

Related Questions