bmusonda
bmusonda

Reputation: 681

Get values by key in the Array of object

I've an array which contains the objects including various key and values. I'm going to pick out the certain values from the Array and check if the specific value is included or not in the Array.

function groupByName (contract) {
 const { age } = contract;

 const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ...
 ];
 ...
}

In order to compare the age in groups array, right now I have to use loop functions and then check one by one. Like

groups.forEach(g => {
 if (g.age === age) {
  ...
 } else {
  ...
 }
});

But I don't like this approach and think there are simple and effective way. Please help me!

Upvotes: 2

Views: 72

Answers (2)

corcre
corcre

Reputation: 21

maybe you can see this function

groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false

or read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

by the way, if you want to execute the if/else snippet in every loop, maybe you should use forEach

Upvotes: 2

R4ncid
R4ncid

Reputation: 7129

you can use filter to create two sublists

like this

const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ]
  
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)

const age30 = withAge(30)

const ageNot30 = withoutAge(30)

age30.forEach(g => {
  console.log('do some stuff with age 30', g)
})

ageNot30.forEach(g => {
  console.log('do some stuff without age 30', g)
})

Upvotes: 3

Related Questions