1

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?

progpro
  • 175
  • 4
  • 15
  • If you want it in the console, what do you want react to do? – Charlie Bamford May 10 '21 at 19:17
  • If it returning true then I have to use `useState` to fire up a action. Otherwise if it is false then I would show alert in that. I just need the concept of matching it with the given word. That's it. Otherwise it would be lengthy question and answer to be asked. – progpro May 10 '21 at 19:20
  • Does this answer your question? [How to determine if Javascript array contains an object with an attribute that equals a given value?](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) – Henry Ecker May 10 '21 at 19:20
  • Specifically [this answer](https://stackoverflow.com/a/8217584/15497888) – Henry Ecker May 10 '21 at 19:20

3 Answers3

3

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);
T J
  • 42,762
  • 13
  • 83
  • 138
1

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);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

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);
fortunee
  • 3,852
  • 2
  • 17
  • 29