Implementing a project using Vue.js and Vuex, I am retrieving data from an API that functions as a content-management system. The product class in the CMS possesses numerous properties that can be populated by the user, such as;
{
"title": "Handbrause rot",
"price": 500,
"description": "Hello World",
...
}
and more. To streamline my application, I aim to normalize the object properties since not all are necessary:
const normalizedProducts = [];
for (let i = 0; i < allProducts.length; i++) {
const normalizedProduct = {
productId: allProducts[i].id,
slug: allProducts[i].slug,
productType: allProducts[i].product_type,
title: allProducts[i].title,
description: allProducts[i].description,
teaser_image: allProducts[i].teaser_image,
images: allProducts[i].images,
new: allProducts[i].new,
topseller: allProducts[i].topseller,
brand: allProducts[i].brand
}
normalizedProducts.push(normalizedProduct);
return normalizedProducts;
}
The issue arises when empty fields in the API return as undefined
. This causes problems where if one property is undefined, the entire program crashes with errors like
TypeError: null is not an object (evaluating 'allProducts[i].brand]')
.
While it's possible to implement if-clauses or try-catch statements for each property to prevent crashing, is there a cleaner solution to this dilemma?
Sample data:
[
{
productId: 1,
slug: 'One',
productType: 'Two',
title: undefined,
description: 'Three',
teaser_image: 'Four',
images: 'Five',
new: undefined,
topseller: undefined,
brand: undefined,
},
]