Reputation: 405
I have JSON data in this format:
{
"head": {
"heading": ["header1", "header2", "header3"]
},
"body": {
"elements": [{
"header1": {
"value": "value1"
},
"header2": {
"value": "value2"
}
"header3": {
"value": "value3"
}
},
{
"header1": {
"value": "value1"
},
"header2": {
"value": "value2"
}
"header3": {
"value": "value3"
}
}
]
}
I can't predict the number of values in headings. So, I initially parsed the values in headings and stored in an array. Later while printing the body elements. I wrote the following code
// data has the parsed json file
var heading = [];
data.head.heading.forEach(function(head) {
heading.push(head);
});
data.body.elements.forEach( function(elem) {
for (var head in the heading) {
var header = heading[head];
alert(elem.header.value); //not accessing value inside header
}
});
On using values.header.value
it needs to access value inside header1
, header2
and header3
of each elem but it is returning an error
TypeError: elem.header is undefined
It is taking the value as the header instead of value inside the variable header. Is there any way to make it access the values inside the variable header? thanks in advance
Upvotes: 1
Views: 34
Reputation: 337714
You need to access the object using bracket notation as the value of header
needs to be used as the key, not the literal word 'header`, eg.
elem[header].value
Also, your first loop is entirely redundant, as you're just copying an array you already have access to. Try this:
data.body.elements.forEach(function(elem) {
for (var head in data.head.heading) {
var header = data.head.heading[head];
console.log(elem[header].value);
}
});
Finally, note that this can be made even more succinct by using another nested forEach()
call to iterate data.head.heading
:
var data = {
"head": {
"heading": ["header1", "header2", "header3"]
},
"body": {
"elements": [{
"header1": { "value": "value1" },
"header2": { "value": "value2" },
"header3": { "value": "value3" }
},
{
"header1": { "value": "value1" },
"header2": { "value": "value2" },
"header3": { "value": "value3" }
}]
}
}
data.body.elements.forEach(function(elem) {
data.head.heading.forEach(function(header) {
console.log(elem[header].value);
});
});
Upvotes: 1