I am new to react and trying to implement all the key and values of a JSON object in my web page. I have a below JSON structure. I want all the keys and values to be printed in my web page where key should be printed as labels.
{
key1: value1,
key2: value2,
key3: value3,
key4:{
k1: val1,
k2: {
p1: v1,
p2: v2,
p3: v3
}
}
}
I have written the below code to get the keys and values of this JSON.
getValues() {
let arr = [];
arr = Object.keys(this.props.myArr).map(key =>
<div key={this.props.data[key]} className=row>
<div className=col-xs-6>{key}</div>
<div className=col-xs-6>{this.props.myArr[key]}
</div>
</div>
)
return arr;
}
render() {
return (
<div>
<Header />
<div className=content>
{this.getValues()}
</div>
</div>
)
}
}
props.myArr has the entire object.
I am able to print the keys and values but not the nested object under key4(p1,p2,p3). I want all the keys along with its values to be printed one after another in my web page. Can someone tell me where am i going wrong and how to access all the keys (as labels) and values of the JSON object.
Edited-
const myObj = {
key1: value1,
key2: value2,
key3: value3,
key4: {
k1: val1,
k2: {
p1: v1,
p2: v2,
p3: v3
}
}
}
class Details extends React.component{
constructor(){
this.getValues = this.getValues.bind(this);
}
getValues() {
let arr = [];
arr = Object.keys(myObj).map(key =>
<div key={myObj[key]} className=row>
<div className=col-xs-6>{key}</div>
<div className=col-xs-6>{myObj[key]}
</div>
</div>
)
return arr;
}
generateData(myObj) {
const newData = Object.keys(myObj).reduce((result, currentKey) => {
if (typeof myObj[currentKey] === 'string' || myObj[currentKey] instanceof String) {
const elementToPush = getValues(currentKey, myObj[currentKey]);
result.push(elementToPush);
} else {
const nested = generateData(myObj[currentKey]);
result.push(...nested);
}
return result;
}, []);
return newData;
}
render() {
return (
<div>
<Header />
<div className=content>
{this.generateData(myObj)}
</div>
</div>
)
}
}
}
P.S I am using getValues with map function to retrieve first level of key and values as the provided syntax by you under generateElement() gives me error.