1

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,

    MachineName
    region 
    zones
    ipAddr
    subnet 

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'}
1
  • Object.keys returns an array of key names, therefore, your return line should look like return (<h4 k={val}>{value[val]}</h4>). Maybe naming your variables with meaningful names would have helped. Commented Feb 20, 2018 at 14:49

3 Answers 3

8

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

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

Comments

3

Just use Object.entries:

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

Comments

1

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]).

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.