others - Javascript - 处理大量嵌套对象和数组时处理错误的正确方法

143 5

我的数据结构(condensed )


const data = {


"cars": [


 {


"name":"toyota",


"sedan": {


"2d": [


 {


"name":"corolla",


"year": 2020


 },


 {


"name":"supra",


"year": 1986


 }


 ]


 }


 }


 ]


};



要按名称查找对象,我将执行以下操作:


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 } ]



有条件检查:


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 } ]



使用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 } ]



我的问题是,首选/行业标准做法是什么?。

  • A
  • try {A.B.C.D} catch {}
  • 其他方法?

我的要求很简单。

  • 如果可能,查找匹配项
  • 应用程序在任何情况下都不应中断,

我试图做的是在代码中避免数以百计的

时间: 原作者:

70 0


const match = data.cars?.find(car => car.sedan)


 ?.twoDcars?.sedan?.['2d']?.filter(car => car?.name ==="corolla");



原作者:
75 4

就像这样:


const data = {


"cars": [


 {


"year": 2020,


"make":"toyota",


"model":"corolla",


"type":"sedan",


"doors" : 2


 },


 {


"year": 1986,


"make":"toyota",


"model":"supra",


"type":"sedan",


"doors" : 2


 }


 ]


};



简化代码和生活:)


let results = data


 .cars


 .filter(car => car.type === 'sedan') // all sedans


 .filter(car => car.doors === 2) // two-door sedans


 .filter(car => car.model === 'corolla'); // two-door corollas




let results = data


 .cars


 .filter(car => car.model === 'corolla' && car.doors === 2);



原作者:
...