My data structure (condensed)
const data = {
"cars": [
{
"name": "toyota",
"sedan": {
"2d": [
{
"name": "corolla",
"year": 2020
},
{
"name": "supra",
"year": 1986
}
]
}
}
]
};
To find the object by name, I would do:
const twoDcars = data.cars.reduce(car => car.sedan);
const match = twoDcars.sedan['2d'].filter(car => car.name === "corolla");
console.log(match); //[ { name: 'corolla', year: 2020 } ]
With conditional check:
const twoDcars = data.cars && data.cars.reduce(car => car.sedan);
const match = twoDcars && twoDcars.sedan && twoDcars.sedan['2d'] && twoDcars.sedan['2d'].filter(car => car && car.name === "corolla");
console.log(match); //[ { name: 'corolla', year: 2020 } ]
With try/catch:
let match;
try {
match = data.cars.reduce(car => car.sedan).sedan['2d'].filter(car => car.name === "corolla");
} catch {}
console.log(match); //[ { name: 'corolla', year: 2020 } ]
My question is, what is the preferred/industry-standard of doing this.
- A && A.B && A.B.C && A.B.C.D
- try {A.B.C.D} catch{}
- Some other approach?
My requirement is pretty simple.
- Find the match if possible
- App shouldn't break on any conditions.
What am I trying to do is avoid hundreds of &&
or `try{}catch{}`` everywhere in my code. I can create utility methods whenever possible but with the complex/nested data that I'm dealing with, it is often impossible.