• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Nodejs mapping through an API gives error: Cannot read properties of null

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

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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.

Answer:

Try using optional chaining:
sku: row.c[1]?.v || '',

If you have better answer, please add a comment about this, thank you!

dictionary javascript node.js
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: std::regex_replace to replace multiple combinations

26/03/2023

Resolved: How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?

26/03/2023

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.