Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nodejs mapping through an API gives error: Cannot read properties of null

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sku: row.c[1].v || '',

but that didn’t help.

>Solution :

Try using optional chaining:

sku: row.c[1]?.v || '',
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading