Lately, I've been working hard to streamline my code and eliminate nested for-loops / forEach methods in order to optimize the process. However, I've hit a roadblock with a specific task. I have an array of objects that includes another array of objects within it. I know how to extract attributes from the inner array using separate functions, but my challenge is extracting attributes from both arrays without resorting to nested loops.
Below is an example of the data structure:
let data = [{Id: '1234', Server: 'prime', Status: 'open', Connections: [{Type: 'xxr', ConID: '1222'}]},
{Id: '1214', Server: 'prime', Status: 'open', Connections: [{Type: 'xxh', ConID: '1111'}, {Type: 'xxh', ConID: '1112'}]},
{Id: '1233', Server: 'tif', Status: 'closed', Connections: [{Type: 'xml', ConID: '1212'}, {Type: 'xxr', ConID: '1233'}, {Type: 'xxh', ConID: '1111'}]}]
The current method involves pushing the necessary data to a new array:
let newArray = [];
data.forEach(server => {
let temp = server.Connections;
temp.forEach(obj => {
let newObj = {
ServerID: server.ID,
Server: server.Server,
Status: server.Status,
ConnectionID: obj.ConID
}
newArray.push(newObj);
})
})
I am looking for a way to potentially use map instead of forEach to populate newArray
, while still accessing attributes from both arrays simultaneously. Any suggestions or solutions would be greatly appreciated!