Calvin Seng
Calvin Seng

Reputation: 193

Filter Json data and make into a Variable

I am not too good with filter or map or transform the JSON data that I retrieved from server and looking for someone to guide me out in this function that I tried which successfully retrieve the JSON data. However, I am looking for a way to just retrieve the id from each key and make the id into a variable which can be used in another function when doing a POST or PUT function in the same Typescript. Thanks in advance.

  getActivities() {
    var service = this;
    let url = service.appConfig.Shop_URL + "/wp-json/erp/v1/crm/activities?type=task";
    url = this.initUrl(url, '');
    var headers = new Headers();
    headers.append('Authorization', 'Bearer ' + service.userService.token);
    headers.append('Content-Type', 'application/json');
    return new Promise(function (resolve, reject) {
      service.http.get(url, { headers: headers }).pipe(map(res => res.json())).subscribe(data => {
        if (data) {
          service.cachedData = data;
          console.log(data);
          resolve(service.cachedData);
        }
        else {
          reject();
        }
      });

    });
  }

JSON Data

(2) [{…}, {…}]
0: {id: 3, type: "task", contact_id: 391, contact_details: {…}, created_by: {…}, …}
1: {id: 1, type: "task", contact_id: 390, contact_details: {…}, created_by: {…}, …}

Upvotes: 1

Views: 579

Answers (3)

kiran kumar
kiran kumar

Reputation: 110

map function is used map each element form the array and returns and make a new array in id variable. map function is only used in array

var data= [{id:12,name:"kiran"},{id:21,name:"hey"}];
var id=data.map((element,i)=>(element.id));

Upvotes: 1

Harshad
Harshad

Reputation: 61

I believe the way to retrieve id would be

json_variable_name[index].get("id")    

Since it is a dictionary, we use the get method. Hope this helps.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222722

You need to use Array.map

this.ids = data.map(x => x.id);

DEMO

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}];
    
 
var data = result1.map(t=>t.id);
console.log(data);

Upvotes: 0

Related Questions