How can i access values in an array of Objects using typescript with angular 9?

Viewed 286

I am trying to retrieve values from a table in quickbase. image of quickbase table

this is what i have so far.... service.ts

    public getNativeFields(){
        let headers = new HttpHeaders().set("QB-Realm-Hostname", "xxxxxx.quickbase.com").set("Authorization", "QB-USER-TOKEN xxxxxx_xxx_xxxxxxxxxxxxxxxxxxxxxxxxx");
    
        let requestBody = {
          "from": this.someTableTableId,
          "select": [6,7]
        }
        return this.httpClient.post(`${this.apiURL}/records/query?appId=${this.appId}`, requestBody, { headers })
 
    }

in my component.ts I have...

    ngOnInit(): void {
        let list= this.apiService.getNativeFields();
        console.log("list is" );
        console.log(list);
        list.forEach(element=>{
          this.nativeVersions.push(element);
        })
        console.log("native versions");
        console.log(this.nativeVersions);
      }

this log returns

image of array of object that was logged into console

how do I extract the {value:"1.0.0"} and {value:"1.0.5"}

2 Answers

It should work to retrieve values:

this.nativeVersions[0].data[0]["6"] //{value:"1.0.0"}
this.nativeVersions[0].data[1]["6"] //{value:"1.0.5"}

Try a dynamic generation of the fields, this way you wont have to worry about which index was for version of notes

From the Object, we can see we have

[
  {
     data: [...],
     fields: [...]
  }
]

The fields define how the data structure is, so we can generate the a simpler object through the map operator. See below code

  constructor(private apiService: ApiService) {}
  list$ = this.apiService.getNativeFields();
  allVersions$ = this.list$.pipe(
    map(list =>
      (list.map(({ fields, data }) =>
        data.map(item =>
          fields.reduce((prev, next) => {
            return { ...prev, [next.label]: item[next.id]["value"] };
          }, {})
        )
      ) as any).flat()
    ),
    map(item => item.map(({ version }) => version))
  );
  ngOnInit() {
    this.allVersions$.subscribe({
      next: items => console.log(items)
    });
  }

See this demo on stackblitz

NB .flat() function is only available in es2019. This post will help with any challenges Typescript flatMap, flat, flatten doesn't exist on type any[]

Related