1

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.

1

3 Answers 3

5

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);

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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){
    ...
   }
 })`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.