If I had this schema:
[{
"Id": 2,
"Prizes": [{
"Id": 5,
"Status": 0,
"ClaimCode": "PN0016CXC1WPM64P",
"User": {
"FirstName": "John",
"SecondName": "Doe",
},
"DrawId": 2,
"PrizeId": 22,
"Prize": null
}]
}]
How could I get the first name or any value under object User that is in array prizes, that is in the main JSON?
I have tried this:
const response = JSON.parse(this.responseText);
response.Prizes[0].User.forEach(function(a) {
output += `<li>${a.FirstName}</li>`;
});
But getting the error undefined, I believe it can be extracted but only need right syntax. Or this can't be done with for loop?
3 Answers 3
First of all Response is an Array and User is an object, this should be working :
const response = JSON.parse(this.responseText);
response.map((resp) => {
resp.Prizes.map((prize) => {
output += `<li>${prize.User.FirstName}</li>`;
})
})
6 Comments
Since you have an array of objects, and inside the object an array of values (Prizes), you can use nested Array.forEach() calls to get the internal values, wrap them with a string, and push to the items array:
const response = [{"Id":2,"Prizes":[{"Id":5,"Status":0,"ClaimCode":"PN0016CXC1WPM64P","User":{"FirstName":"John","SecondName":"Doe"},"DrawId":2,"PrizeId":22,"Prize":null}]}];
const items = [];
response.forEach((o) =>
o.Prizes.forEach((p) =>
items.push(`<li>${p.User.FirstName}</li>`)
));
list.innerHTML = items.join('');
<ul id="list"></ul>
Comments
As you have multidimensional array and you need to use Prizes as inside of array.
So first you can combine all Prizes into one using reduce() and the Spread_syntax then after you use map() with join mehod to get the required result.
DEMO
const response = [{"Id":2,"Prizes":[{"Id":5,"Status":0,"ClaimCode":"PN0016CXC1WPM64P","User":{"FirstName":"John","SecondName":"Doe"},"DrawId":2,"PrizeId":22,"Prize":null}]}];
let res = response.reduce((r,{Prizes}) =>[...r,...Prizes],[]).map(({User})=>`<li>${User.FirstName}</li>`).join('');
document.querySelector('ul').innerHTML =res ;
<ul></ul>
responseis an Array, not a plain Object.forEachshould be used on an Array.for(let key in response[0].Prizes[0].User), but I don't think you neeed a loop for this.