In the project I'm currently working on, I have two endpoints that provide different information. The 'categories' endpoint supplies me with category names and their corresponding id values, while the 'products' endpoint only gives me the category id values. My goal is to match the id values from both endpoints and assign the respective category names to the products.
To achieve this, I initially attempted to synchronize the data using a nested loop structure, but it led to verbose and unstable code. The instability arises from the inconsistent retrieval of data, sometimes returning results and sometimes not, without any clear error indication. How can I optimize the code to be concise and more reliable?
data:
products: {
items: [{ categoryName: '' }],
},
created(){
fetch('example/products')
.then((response) => {
return response.json();
})
.then((data) => {
this.products = data;
});
fetch('example/categories')
.then((response) => {
return response.json();
})
.then((data) => {
this.categories = data;
this.pushNametoCategoryNames();
});
}
methods() {
pushNametoCategoryNames() {
for (let i = 0; i < this.products.items.length; i++) {
for (let j = 0; j < this.categories.length; j++) {
console.log(this.products);
console.log(this.categories[j]);
if (this.products.items[i].categoryId == this.categories[j].id) {
this.products.items[i].categoryName = this.categories[j].name;
}
}
}
},
}