I'm trying to process data from an API. (I have no control over the API output). Here's an example of the code :
const json = [
{
c: [
{ v: 'Product 1' },
{ v: '1234102' },
{ v: 'IN STOCK' },
null,
{ v: 'Access From All Warehouses' },
],
},
{
c: [
{ v: 'Product 2' },
{ v: '1234608' },
{ v: 'OUT OF STOCK' },
{ v: '6/2022' },
{ v: 'Access From All Warehouses' },
],
},
{ c: [{ v: 'Category Name' }, null, null, null, { v: null }] },
{
c: [
{ v: 'Product 3' },
{ v: '1234942' },
{ v: 'OUT OF STOCK' },
{ v: 'No ETA ' },
{ v: 'Access From All Warehouses' },
],
},
];
const result = json.map((row) => {
return {
name: row.c[0].v,
sku: row.c[1].v,
inventory: row.c[2].v,
eta: row.c[3].v,
access: row.c[4].v,
};
});
console.log(result);
When I get to the category name or a product with missing information the map function gives an error of "Cannot read properties of null". What is a good solution to bypass that issue?
I've tried using somethinhg like:
sku: row.c[1].v || '',
but that didn't help.
CodePudding user response:
Try using optional chaining:
sku: row.c[1]?.v || '',