简体   繁体   中英

How to access an array of objects inside another array of objects in angular 4

I have a api response that return this :

{
"code": 0,
"message": "hierarchy list",
"payload": [

{
  "id": 2,
  "name": "nameParent",
  "code": "WUcw",
  "childsOfPayload": [
    {
      "id": 5,
      "name": "NameChild1",
      "code": "ozyW",
      "status": "Active",
      "childsofChildOfPayload": [
        {
          "id": 8,
          "name": "NameChild2",
          "code": "aitq",
          "order": 30,

        },
 ]}]}]}

I am trying to get the differents objects in each childs, ChildOfPayload and childOfChildOfpayload.

First I've returned the different name value of payload:

    getAllPayloadName() {
   this.userService.getName().subscribe(
    data => {
    this.values= data;
   }
 );

}

But what must I do to get the name of each child assosiated to the different parent value!

I mean in this case.

       NameChild1 
       NameChild2 

I've tried this:

manipulateDataa() {
this.values.subscribe(x => { 
x.payload.foreach((y:any) => { 
  y.childs.foreach((z:any) => { 
    console.log( z.name) 
   }) 
  })
 })
}

then call it in getAllPayloadName, but still don't work. What could be wrong?

You could do something like this to get your desired output. Here you can read more about forEach loop which I have used.

 data = { "code": 0, "message": "hierarchy list", "payload": [ { "id": 2, "name": "nameParent", "code": "WUcw", "childsOfPayload": [ { "id": 5, "name": "NameChild1", "code": "ozyW", "status": "Active", "childsofChildOfPayload": [ { "id": 8, "name": "NameChild2", "code": "aitq", "order": 30, }, ]}]}]} names = [] function iterator (obj, namesArr){ Object.keys(obj).forEach(key => { if(key === "name") { namesArr.push(obj[key]) } else if(typeof obj[key] === "object") { iterator(obj[key][0], names) } }) } iterator(data.payload[0], names) console.log(names) 

if the api result structure is strongly type and will not change u can access the child payload name by this line

    console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].name));
    console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].childsofChildOfPayload[0].name));

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