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?