Reputation: 413
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'}
Upvotes: 1
Views: 13144
Reputation: 104399
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));
Upvotes: 8
Reputation: 138307
Just use Object.entries:
{Object.entries(value).map(([key, value]) => {
return (<h4>{key} : {value}</h4>);
}) }
Upvotes: 3
Reputation: 67296
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]
).
Upvotes: 1