Nagesh Katna
Nagesh Katna

Reputation: 717

how to check if a object in an array contains a key or not in React

I am a novice to React and I am stuck in something. I have an array in the state which contains an object in it. The array looks like this:

myVar = [
      {
      "a": 1,
      "b":2
  },
  {
    "c":1,
    "d":1
  },
  {
    "e":"",
    "f":4
  }
  ];

I want to check somehow that does the array contains a key a or c or f by using this.state.myVar syntax. It doesn't matter what value it contains. It can be null.

I couldn't find a way to check it using JSX.

My output depends on it. Like if the array contains a key called a or c or f then it will display data depending on the available key. I can do this part but not sure how can I check for the availability of the key. Please Help me on that.

Upvotes: 1

Views: 18471

Answers (3)

Chris Aby Antony
Chris Aby Antony

Reputation: 813

You can go through each array element by mapping it.

For example

myVar.map( function(item){ console.log(item) } )

Now you can check if the object item contains any of the required keys by using any one of the methods mentioned here. One method is as follows:

`myVar.map( function(item){ 
   if("a" in item){
    ...
   }
 })`

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104369

I couldn't find a way to check it using JSX.

This is not related to JSX or React. You need to iterate the array and check.


You can use any loop and hasOwnProperty to check whether the object has that key or not. One possible way to check is using #Array.some.

Like this:

myVar = [
  {
    "a": 1,
    "b":2
  },
  {
    "c":1,
    "d":1
  },
  {
    "e":"",
    "f":4
  }
];

let isKeyPresent = myVar.some(el => {
  if(el.hasOwnProperty('a') || el.hasOwnProperty('b') || el.hasOwnProperty('f'))
    return true;
})

console.log('isKeyPresent', isKeyPresent);

Upvotes: 5

Ali BARIN
Ali BARIN

Reputation: 1920

Actually it has nothing to do with React, JSX or another thing other than JavaScript itself. You can check if any of array items contains a key with the snippet below;

arr.some(item => item.hasOwnProperty('propertyName')) // returns boolean

So it will be something as below for your case;

myVar.some(item => item.hasOwnProperty('a'))

You can check this out to see how you can use the code in JSX.

Upvotes: 3

Related Questions