javascript中嵌套数组的最佳实践



我目前正在API响应中使用嵌套数组,并且需要提取一些信息。

在下面的例子中,我想从"PaymentTypeName"中提取值Obj键,我的代码是这样的:

data.forEach(({ ModelList }) => {
ModelList.forEach(({ CountryList }) => {
CountryList.forEach(({ PaymentTypeList }) => {
PaymentTypeList.forEach(({ PaymentTypeName }) => {
console.log(PaymentTypeName);
});
});
});
});

,"data"是我的API响应。

我想知道:有没有比这个嵌套的"forEach"更好/更干净的代码方法?电话吗?这是一种不好的做法吗?

如果你能简化数据结构,那将是最好的方法。

如果结构不在您的控制范围内,那么您编写的方式对于"一次性"提取嵌套数据是可以的。但是,如果您经常在不同的路径上提取嵌套数据,那么编写forEach()将会很费力,您可能需要考虑使用辅助函数来使其更容易。

我写了一个像这样执行的帮助程序:

const paymentTypes = getValuesAtPath(data, ['ModelList', 'CountryList', 'PaymentTypeList', 'PaymentTypeName']);

函数本身使用reduce()并且是递归的。

const data =[
{
"ModelList": [
{
"CountryList": [
{
"PaymentTypeList": [
{
"PaymentTypeName": "paypal"
},
{
"PaymentTypeName": "check"
}
]
},
{
"PaymentTypeList": [
{
"PaymentTypeName": "credit card"
}
]
}
]
},
{
"CountryList": [
{
"AnotherInterestingField": "look at me",
"PaymentTypeList": [
{
"PaymentTypeName": "cash"
}
]
}
]
}
]
}
];
const getValuesAtPath = (data, path) => data.reduce((acc, item) => {
const key = path[0];
const value = item[key];
if (value === undefined) return acc;
// if at end of nested tree
if (path.length === 1){
return [...acc, value];
}
return [...acc, ...getValuesAtPath(value, path.slice(1, path.length))];
}, []);
const result = getValuesAtPath(data, ['ModelList', 'CountryList', 'PaymentTypeList', 'PaymentTypeName']);
console.log(result);

这个帮助器现在也可以被重用来提取其他属性:

getValuesAtPath(data, ['ModelList', 'CountryList', 'AnotherInterestingField'])

最新更新