Home  >  Forum  >  Angular
Post New Query

How to store a json data in array only for particular id in angular 7



Asked on November 27, 2019
I have a REST API from which i am fetching the json data and storing them in array.The API looks like below:
[
  {
    "id": "100",
    "name": "Person1",
    "number": "+91-8980439023"
  },
  {
    "id": "102",
    "name": "Person2",
    "number": "+91-5980339023"
  },
  {
    "id": "105",
    "name": "Person3",
    "number": "+91-8980439023"
  },
  {
    "id": "101",
    "name": "Person4",
    "number": "+91-8980439023",
    "parent": "105"
  },
  {
    "id": "110",
    "name": "Person5",
    "number": "+91-8980439023"
  },
  {
    "id": "115",
    "name": "Person6",
    "number": "+91-9834295899",
    "parent": "100"
  }
]

Some of the data have "parent" field.The value in the "parent" field is the "id" of the other data.Now i want to store these data which have reference in the "parent" field of other data in a separate array.
How can i do that without using two for loops in a simple scalable way?



Replied on November 28, 2019
Try the following code.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  template: ` `
})
export class TestComponent implements OnInit {
parentData = [];
ngOnInit() {
    JSON_DATA.forEach(row => {
   if ( row.parent !== undefined) {
this.parentData.push(row);
   }
    });
    console.log(this.parentData);
  }
}


const JSON_DATA = [
  {
    "id": "100",
    "name": "Person1",
    "number": "+91-8980439023"
  },
  {
    "id": "102",
    "name": "Person2",
    "number": "+91-5980339023"
  },
  {
    "id": "105",
    "name": "Person3",
    "number": "+91-8980439023"
  },
  {
    "id": "101",
    "name": "Person4",
    "number": "+91-8980439023",
    "parent": "105"
  },
  {
    "id": "110",
    "name": "Person5",
    "number": "+91-8980439023"
  },
  {
    "id": "115",
    "name": "Person6",
    "number": "+91-9834295899",
    "parent": "100"
  }
];



Replied on November 28, 2019
Thanks @Mukesh. The solution was right in front my eyes and i could not see.

Write Answer




©2019 concretepage.com | Privacy Policy | Contact Us