Others have demonstrated how you can use dynamic object keys. But another possibility is to restructure that object on the fly to be more useful in other work. This may be entirely irrelevant to you, but I find it useful to convert objects in formats like this into more useful ones when doing my work with them.
So if we had a magic restructure
function, we could be working instead on data that looks like:
{
"admin": [
{
"id": "123",
"role": "abc"
},
{
"id": "123",
"role": "abc"
},
{
"id": "123",
"role": "abc"
},
{
"id": "123",
"role": "abc"
},
{
"id": "123",
"role": "abc"
}
]
}
which is much easier to work with. (updatedData.admin.forEach (...)
, for instance.)
But it turns out not too hard to build our restructure
on top of two helpers I use regularly:
const setPath = ([p, ...ps]) => (v) => (o) =>
p == undefined ? v : Object .assign (
Array .isArray (o) || Number .isInteger (p) ? [] : {},
{...o, [p]: setPath (ps) (v) ((o || {}) [p])}
)
const hydrate = (xs) =>
xs .reduce ((a, [p, v]) => setPath (p) (v) (a), {})
const restructure = (o) =>
hydrate (
Object .entries (o)
.map (([k, v]) => [
k .split ('_') .map ((p) => /^\d+$/ .test (p) ? Number(p) : p),
v
])
)
let usrData = {
admin_0_id: "123",
admin_0_role: "abc",
admin_1_id: "123",
admin_1_role: "abc",
admin_2_id: "123",
admin_2_role: "abc",
admin_3_id: "123",
admin_3_role: "abc",
admin_4_id: "123",
admin_4_role: "abc"
}
console .log (restructure (usrData))
.as-console-wrapper {max-height: 100% !important; top: 0}
Here, setPath
takes a path such as ['admin', 2, 'role']
, and a value such as 'abc'
and an object and returns a copy of that object, setting the value at that path, creating any intermediate nodes as needed. hydrate
takes an array of path-value pairs and creates a brand new object as needed.
Our restructure
function then splits the keys of an object on _
, converts any nodes containing only digits to numbers and then passes these new path arrays (alongside the corresponding values) to hydrate
to create a more fully-realized object described by your flat structure and its _
-joined keys.
As I said, this might not meet any of your requirements. But it also might, and it's a useful way to look at the problem.