I'm currently working with nested arrays in an API response, and there is some info I need to extract.
In the example below, I want to extract the values from the "PaymentTypeName" obj key, and my code looks like that:
data.forEach(({ ModelList }) => {
ModelList.forEach(({ CountryList }) => {
CountryList.forEach(({ PaymentTypeList }) => {
PaymentTypeList.forEach(({ PaymentTypeName }) => {
console.log(PaymentTypeName);
});
});
});
});
Where "data" is my API response.
I want to know: is there a better/cleaner code approach than this nested "forEach" calls? Is it considered a bad practice?
If you can simplify the data structure, that will be the best approach.
If the structure is outside your control, the way you have written it is fine for a 'one-off' extraction of nested data. However, if you're constantly extracting nested data at different paths, writing forEach() will be laborious and you might want to consider a helper function to make it easier.
I wrote a helper that is executed like so:
const paymentTypes = getValuesAtPath(data, ['ModelList', 'CountryList', 'PaymentTypeList', 'PaymentTypeName']);
The function itself uses reduce() and is recursive.
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);
This helper can now be reused to extract other properties too:
getValuesAtPath(data, ['ModelList', 'CountryList', 'AnotherInterestingField'])