简体   繁体   中英

JSON - object in array in object - how to parse through loop with JS?

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?

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>`;

    })
})

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM