0

How to get the key from object in

{this.state.data.map((object, index) => (
      <div>object.key</div>

    ))}

For example if this.state.data was

 [{mykey1:23},{mykey2:24},{mykey3:34}]

I would want it to return

 <div>mykey1</div>
 <div>mykey2</div>
 <div>mykey3</div>
3
  • Is the key name really what you want and not the value? (eg, <div>23</div>) Commented May 26, 2019 at 0:51
  • Yes I want the key name Commented May 26, 2019 at 0:51
  • 1
    Possible duplicate of Javascript get object key name Commented May 26, 2019 at 0:53

2 Answers 2

2

Use Object.keys():

{this.state.data.map(obj => <div>{Object.keys(obj)[0]}</div>)}
Sign up to request clarification or add additional context in comments.

1 Comment

I believe it's not an object but an array of object, thus it'd return array indices ["0", "1", "2"], not keys
0

You are not interpolating the value you want to render to start with. You would have to put values that you want to be evaluated within curly brackets for them to be rendered from your states/props. Though I'm assuming your example was typed in haste and that is not the reason why this is not working for you. To get keys defined in an object you would have to use Object.keys() which returns an array of strings with all the keys. Then you could loop over the resulting array and render them within your JSX view.

Here's a working fiddle for your reference: https://jsfiddle.net/2q19rpaz/

let data = [{mykey1:23},{mykey2:24},{mykey3:34, mykey4:34}];
return data.map((object, index) => {
    return Object.keys(object).map((key, index) => {
        return (<div>{key}</div>);
    })
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.