Seeking a way to extract unique values from a JSON array.
The data is fetched through the fetch API, which can be iterated through easily.
[please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts()]
products =
[
{
"name": "APPLE 27 inch THUNDERBOLT DISPLAY",
"show_room": "A iCenter",
"stock": "1",
"type": "DISPLAYS",
"category": "APPLE",
"id": "101"
},
{
"name": "APPLE WIRELESS KEYBOARD",
"show_room": "B iCenter",
"stock": "2",
"type": "MOUSE",
"category": "MAC ACCESSORIES",
"id": "107"
}
]
An error occurs when attempting to execute the function: getDistinctCategoryValues()
This snippet is from my .ts file
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.page.html',
styleUrls: ['./product-list.page.scss'],
})
export class ProductListPage implements OnInit {
constructor(private dataService: DataService,
private router: Router) {
this.GetAllProducts();
this.getDistinctCategoryValues();
}
products: any;
ngOnInit() {
}
async GetAllProducts() {
const response = await this.dataService.GetProducts();
const dataService = await response.json();
this.products = dataService;
console.log(this.products);
}
getDistinctCategoryValues() {
const lookup = {};
const result = [];
console.log(this.products);
for (const item of this.products) {
const currentVar = item.category;
if (!(currentVar in lookup)) {
lookup[currentVar] = 1;
result.push(currentVar);
}
}
console.log(result);
return result;
}
}
When running getDistinctCategoryValues(), an error is thrown:
ERROR Error: Uncaught (in promise): TypeError: this.products is not iterable.
A peculiar issue arises where,
- While
console.log()
withinGetAllProducts()
shows all data correctly stored in the products variable - Subsequent
console.log()
withingetDistinctCategoryValues()
displays the product variable as undefined
Perplexed on what went wrong. Why does the data disappear just one line later? [refer to the constructor]. The API runs smoothly without any errors.
[By the way, utilizing https://www.npmjs.com/package/json-server for handling JSON]