0

I have an object (a return from a graphQl query), that I am iterating over in order to make the data structure simpler before using the data. There are some non-required field in the data model, and I would like to use the data when it's there, and default to undefined when it is not.

This is my current function:

const parseNovice = data => {
  return data.allContentfulNovica.edges.map(edge => {
    return {
      createdAt: edge.node.createdAt,
      id: edge.node.id,
      slika: edge.node.slika.file.url || undefined,
      tekst: edge.node.tekst.tekst || undefined,
      naslov: edge.node.naslov
    };
  });
};

The error I am getting is:

TypeError: Cannot read property 'file' of null

In other words the file for the image is missing, and therefore the file property is not defined. Is there a way for me to default to undefined regardless of which of the properties in the chain is missing?

Should I be using a try/catch for this?

1 Answer 1

1

Not in a clean native way. You would need to do undefined checks the whole way down. You should consider how lodash impliments _.get(). It wraps the logic for doing the undefined checks. So you may want to consider using that or writing your own utility function if you find yourself doing these deep undefined checks often.

Otherwise you'll have to write something like this:

let edge;

let thing = {
  prop: edge !== undefined && edge.node !== undefined && edge.node.tekst !== undefined && edge.node.tekst.tekst !== undefined ? edge.node.tekst.tekst : undefined,
  prop2: _.get(edge, "node.tekst.tekst")
}

console.log(thing); // undefined

edge = {
  node: {
    tekst: {
      tekst: "foo"
    }
  }
};

thing = {
  prop: edge !== undefined && edge.node !== undefined && edge.node.tekst !== undefined && edge.node.tekst.tekst !== undefined ? edge.node.tekst.tekst : undefined,
  prop2: _.get(edge, "node.tekst.tekst")
}

console.log(thing); // foo
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, decided to use lodash since I'm importing it anyway, forgot about the .get() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.