My array contains multiple arrays and to access the objects, I have used multiple forEach. How do I handle using multiple foreach loops? Kindly suggest an equivalent method to avoid this chaining. See the below snippet and suggest a better solution to optimize my code.
var v = [
{
"company_name": "Apple",
"company_code": "AP",
"states": [
{
"state_name": "California",
"state_code": "CA",
"locations": [
{
"location_name": "USA - New York",
"location_code": "US - NY"
},
{
"location_name": "USA - San Francisco",
"location_code": "US - SF"
}
]
},
{
"state_name": "Rajasthan",
"state_code": "RJ",
"locations": [
{
"location_name": "Udaipur",
"location_code": "UDR"
},
{
"location_name": "Jaipur",
"location_code": "JP"
}
]
}
]
}
]
var AllData=[]
for (let i = 0; i < v.length; i++) {
const data = v[i];
//console.log(data);
data.states.forEach((state) => {
state.locations.forEach((location) => {
const ELEMENT_DATA = {
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name,
};
AllData.push(ELEMENT_DATA);
});
});
}
console.log(AllData);