简体   繁体   English

JSON-对象数组中的对象-如何使用JS解析循环?

[英]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? 如何在数组奖品(即主要JSON)中的对象User下获得名字或任何值?

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? 还是用for循环不能做到这一点?

First of all Response is an Array and User is an object, this should be working : 首先,Response是一个数组,User是一个对象,这应该可以工作:

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: 由于您有一个对象数组,并且在对象内部有一个值数组( Prizes ),因此可以使用嵌套的Array.forEach()调用来获取内部值,用字符串包装它们,然后推入items数组:

 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. 由于您具有多维数组,因此需要在数组内部使用Prizes

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. 因此,首先,你可以结合所有Prizes使用到一个reduce()Spread_syntax然后使用后map()与加入mehod获得所需的结果。

DEMO 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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