I've implemented a solution for the problem below with loops, but I'm sure there is a better way. Consider this data structure:
let arr = [
{
"id": "000701",
"status": "No Source Info",
"sources": []
},
{
"id": "200101",
"status": "Good",
"sources": [
{
"center": "H2",
"uri": "237.0.1.133",
"program": 1,
"status": "Good",
"state": {
"authState": "authorized",
"lockState": "locked"
}
}
]
},
{
"id": "005306",
"status": "Good",
"sources": [
{
"center": "H1",
"uri": "237.0.6.5",
"program": 3,
"status": "Good",
"state": {
"authState": "authorized",
"lockState": "locked"
}
},
{
"center": "H1",
"uri": "237.0.6.25",
"program": 3,
"status": "Good",
"state": {
"authState": "authorized",
"lockState": "locked"
}
}
]
}
]
I want to learn the most efficient way to reduce it to a map with key-value pairs of only the nested uri and state values from the sources array. The final result should look like this:
let stateMap = {
"237.0.1.133": { "authState": "authorized", "lockState": "locked" },
"237.0.6.5": { "authState": "authorized", "lockState": "locked" },
"237.0.6.25": { "authState": "authorized", "lockState": "locked" }
}
I have a partial solution that returns a map of each source array, but I'm struggling to get it all into one structure.
let allStates = arr.reduce((acc, object) => {
if (object.sources.length) {
let sourceMap = object.sources.reduce((map, obj) => {
map[obj.uri] = obj.state
return map
}, {})
acc[acc.length] = sourceMap
return acc
}
// delete all unused keys and somehow flatten the objects?
}, {})
Would recursion be an option here or what would be a better approach?