I have the below code which executes all keys and values of the nested JSON. Its working fine but whenever the value is null for any key, the code breaks at reduce function. I would like to display the null value as well.I tried to handle null and undefined scenario in else if but that is not working. Below is the code I have written.It must be a minor change which I am missing out.
const myObj = {
"key1": "value1",
"key2": null,
"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() {
return (
<div key={k} className="row">
<div className="col-xs-6">{k}</div>
<div className="col-xs-6">{v}</div>
</div>
)
}
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>
)
}
}
Object.keys(...), because you are calling generateData withnull.