dper
dper

Reputation: 904

Iterate through JSON object in angular 6

I am new to Angular and probably this might be a silly question. I am trying to get an api response and save it into an array. My API response looks like :

[
    {
        "name1": {
            "name": "name1",
            "api": {
               //somedata
            },
            "t1p": {
               //somedata
            }
        }
    },
    {
        "name2": {
            "name": "name2",
            "api": {
                //somedata
                }
            },
            "t1p": {
                //somedata
            }
        }
    }
]

I get the response from the code

var data = [];

makeRequest(): void {
      this.http
        .get(this.URL1)
        .subscribe((res: Response) => {
          this.data = res;
          console.log(this.data);
        }, err => console.log(err));
    }

Now I want to fetch the "name" value from each of the JSON object. I tried doing this:

var ids:string = [];

for(let result of this.data){
            ids.push(result.name);
            console.log("Added"+result.name);
          }

But I am not able to achieve the same. Can anyone tell me what is wrong with the same.

Upvotes: 2

Views: 12921

Answers (3)

KShewengger
KShewengger

Reputation: 8269

You can implement it with .map and Object.keys()

const result = data.map(item => Object.keys(item)[0]);

console.log(result);   // ['name1', 'name2']

If you want to perform that method to your http call. You can do so by:

this.http
    .get(this.URL1)
    .pipe(map(res => res.map(item => Object.keys(item)[0])))
    .subscribe((res: Response) => {...});

Upvotes: 2

Muhamamd Omar Muneer
Muhamamd Omar Muneer

Reputation: 885

makeRequest(): void {
      this.http
        .get(this.URL1)
        .pipe((response) => {
         response.map((re,index)=> re['name'+(index+1)]['name'])
        })
        .subscribe((res: Response) => {
          this.data = res;
          console.log(this.data);
        }, err => console.log(err));
    }

I gave the solution by looking at your response API. Now in the subscriber, you will get the only name.

Upvotes: 0

Tuhin Das
Tuhin Das

Reputation: 499

Try this !

for(let i = 0; i < this.data.length; i++ )
{
   for(let key of this.data[i])
   {
      if(this.data[i][key].hasOwnProperty("name"))
         ids.push(this.data[i][key][name]);
   }
}

As your object lies inside another object with key as name.

Upvotes: 0

Related Questions