1

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?

2 Answers 2

1

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)
 

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But I'm sorry , this is not the output that I want , I want for each nameParent its associated child name ..
@G.Ab please post what do you expect in output
I want something like that : console.log("The parent name " + parentName + " it'schild " + the value of name of it's child ( here like example , NameChild1 ) + " who has child " + the value of name of the second child ( NameChild2) ... And , each time that I add another parent name with different child I must have an output that give me the parent with the value of it's child ..
0

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

Comments