简体   繁体   English

如何从地图功能中的对象获取密钥?

[英]How to get key from object in map function?

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 例如,如果this.state.data是

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

I would want it to return 我希望它回来

 <div>mykey1</div>
 <div>mykey2</div>
 <div>mykey3</div>

使用Object.keys()

{this.state.data.map(obj => <div>{Object.keys(obj)[0]}</div>)}

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. 要获得在对象中定义的键,您将必须使用Object.keys()返回包含所有键的字符串数组。 Then you could loop over the resulting array and render them within your JSX view. 然后,您可以遍历结果数组并在JSX视图中呈现它们。

Here's a working fiddle for your reference: https://jsfiddle.net/2q19rpaz/ 这是一个有用的小提琴供您参考: 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>);
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM