The structure of the array I'm working with is as follows (with variable objects inside):
this.selected_sum_version may contain multiple groups:
this.selected_sum_version.sum_item_groups = [
{
"id": 1,
"name": "GROUP 1",
"version_id": 1,
"sum_items": [
{
"id": 1,
"type": "formula",
"sum_item_group_id": 1,
"formula": {
"id": 1,
"name": "Formula NAME",
"sum_item_id": 1
},
...
},
...
]
},
...
]
Each object within this.selected_sum_version.sum_item_groups has a 'type' which can be grid, chart, formula, or text_box.
I need to generate a new array, starting with newArray = [], containing all names based on the type. For example, using the data above, newArray would be:
this.newArray = ['Formula NAME', 'Wei', 'Lan', 'JFM', 'JC'].
Based on the 'type' field in each object, one of 'formula, text_box, grid, or chart' will not be null and will have an id, name, and sum_item_id. The goal is to create newArray with all those names.
The current code provided below accomplishes the task but there might be a more efficient and cleaner way to write it. Any suggestions?
var emptyArray = [];
this.selected_sum_version.sum_item_groups.forEach(element => {
element.sum_items.forEach(elementtwo => {
if (elementtwo.type === 'formula') {
newArray.push(elementtwo.formula.name);
} else if(elementtwo.type === 'grid') {
newArray.push(elementtwo.grid.name);
} else if(elementtwo.type === 'chart') {
newArray.push(elementtwo.chart.name);
} else if(elementtwo.type === 'text_box') {
newArray.push(elementtwo.text_box.name);
}
});
});