简体   繁体   English

如何在对象内部打印元素值使用es6反应

[英]how to print the elements value inside an object react using es6

i have an array of objects and i want to print the content of each element inside this each object, i have tried the method provided in this( Render Object properties in React ) and what i got is just a list of the elements without its values 我有一个对象数组,我想在每个对象中打印每个元素的内容,我尝试了this( React中的Render Object属性)中提供的方法,我得到的只是元素列表,没有其值

state={
  machines: [{
        MachineName: 'A1',
        region: 'west', 
        zones:'west-01',
        ipAddr:'1.1.1.1',
        subnet:'test'}, 
      {
        MachineName: 'A2',
        region: 'west', 
        zones:'west-01',
        ipAddr:'1.1.1.2',
        subnet:'test2'

}]

}
      render() {
const machinespc=this.state.machines.map((value,key)=>{

  return (
    <div>
        <div className="col-md-4" key={key}>
            <div className="dashboard-info">

                {Object.keys(value).map((val, k) => {
                    return (<h4 k={k}>{val}</h4>)
                    })
                }

            </div>
        </div>
    </div>
)

})
  return ( 
{machinespc} ) {machinespc})

and the out put was like below, 输出结果如下

     A1
    west
    west-01
    1.1.1.1
    test'}

so what i want is to print the values of each element inside the object like below: 所以我想要的是打印对象内每个元素的值,如下所示:

  A1 west west-01 1.1.1.1 test'} 

Just use Object.entries: 只需使用Object.entries:

{Object.entries(value).map(([key, value]) => {
      return (<h4>{key} : {value}</h4>);
}) }

You just need to lookup the value from your val : 您只需要从val查找值:

{Object.keys(value).map((val, k) => {
    const theValue = value[val];
    return (<h4 key={k}>{theValue}</h4>)
    })
}

Object.keys(value) will return you an array of all the object's keys. Object.keys(value)将返回一个包含所有对象键的数组。 You then need to get the value ( value[val] ). 然后,您需要获取值( value[val] )。

Issue is you are running loop of keys, so you need to use that key to get the value, Like this: 问题是您正在运行键循环,因此您需要使用该键来获取值,如下所示:

{
    Object.keys(value).map((val, k) => <h4 k={k}>{value[val]}</h4>)
}

Or you can use Object.values , it will return the array of all the values, like this: 或者,您可以使用Object.values ,它将返回所有值的数组,如下所示:

{
    Object.values(value).map((val, k) => <h4 k={k}>{val}</h4>)
}

Check this snippet, you will get a better idea: 查看此代码片段,您将有一个更好的主意:

 let obj = {a:1, b:2}; console.log("keys array = ", Object.keys(obj)); console.log("values array = ", Object.values(obj)); 

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

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