progpro
progpro

Reputation: 195

How to match key value in array of objects

I have array of objects. I want to find the value in key which matches the word and if it's there it should return me true in console otherwise false.

I have array of objects like this:

[
    {
        "groupName": "harry",
    },
    {
        "groupName": "mike",
    }
]

And I want to match this key groupName with value like Amy. As we can see Amy in not there in groupName so it should return me false in console otherwise true if any of the groupName value is Amy.

How to achieve this using Javascript?

Upvotes: 1

Views: 6211

Answers (3)

fortunee
fortunee

Reputation: 4332

React has nothing to do with what you're trying to achieve.

With just Javascript, you can do this using the some Array method like this.

const obj = [
    {
        "groupName": "harry",
    },
    {
        "groupName": "mike",
    }
]

const hasAmy = obj.some(x => x.groupName === 'Amy');
const hasMike = obj.some(x => x.groupName === 'mike');

console.log(hasAmy);
console.log(hasMike);

Upvotes: 1

T J
T J

Reputation: 43166

You can simply use Array.some():

const data = [{
    "groupName": "harry",
  },
  {
    "groupName": "mike",
  }
];

const result = data.some(obj => obj.groupName === 'harry');
console.log(result);

Or Array.find() to get the matching object:

const data = [{
    "groupName": "harry",
  },
  {
    "groupName": "mike",
  }
];

const result = data.find(obj => obj.groupName === 'harry');
console.log(result);

Upvotes: 3

Guerric P
Guerric P

Reputation: 31825

You could use this code (functional code style):

const input = [
    {
        "groupName": "harry",
    },
    {
        "groupName": "mike",
    }
];

const findByPropertyName = name => arr => searched => arr.some(({ [name]: value}) => value === searched);

const findByGroupName = findByPropertyName('groupName');

const notFound = findByGroupName(input)('Amy');
const found = findByGroupName(input)('harry');

console.log(notFound);
console.log(found);

Upvotes: 1

Related Questions