简体   繁体   中英

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

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

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(value).map(([key, value]) => {
      return (<h4>{key} : {value}</h4>);
}) }

You just need to lookup the value from your 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. You then need to get the value ( 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(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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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