Reputation: 232
I'm currently working on a service that returns the following payload:
{
"account1": {
"app1": {
"status": "Online",
"comments": "blah blah",
"events": [
{
"date": "some date",
"generated_by": "some user"
}
]
}
},
"account2": {
"app1": {
"status": "Offline",
"comments": "blah blah bleh",
"events": [
{
"date": "some date",
"generated_by": "some user"
}
]
},
"app2": {
"status": "Online",
"comments": "blah blah",
"events": [
{
"date": "some date",
"generated_by": "some user"
}
]
}
}
}
I'm trying to render a table with the following fields:
-------------------------------
Application | Account | Status
-------------------------------
app1 | account1 | Online
app1 | account2 | Offline
app2 | account2 | Online
Normally this would be easy to do if my payload would be something like a list of objects but I'm kinda stuck here.
I tried to normalize this payload by extracting each of the fields and creating a new payload by doing something like the following:
const extractAccountNumber = Object.values(payload).map(account => ({account: account}))
which would return:
[
{
"account": "account1"
},
{
"account": "account2"
}
]
I wanted to move on to app name the same way and once I get all my fields I would merge the payload. This has proven to be super cumbersome and I'm sure there is a better, more efficient way to achieve this which I'm probably missing. Any feedback would help me a ton to understand how this can be achieved using javascript with or without lodash.
Upvotes: 0
Views: 182
Reputation: 883
Iterating by first level and then by second level:
table = [];
for (accountName in apiResponse) {
account = apiResponse[accountName];
for (appName in account) {
app = account[appName];
table.push({
application: appName,
account: accountName,
status: app.status,
});
}
}
Then table is something like this:
[
{
"application": "app1",
"account": "account1",
"status": "Online"
},
{
"application": "app1",
"account": "account2",
"status": "Offline"
},
{
"application": "app2",
"account": "account2",
"status": "Online"
}
]
Upvotes: 2
Reputation: 420
Can try something like
Object.entries(o).map(([accountName, value]) => ({
account: accountName,
apps: Object.entries(value)
.map(([appName, value]) => ({name: appName, ...value }))
}))
Not sure about structure. Where to put app1 from account2 in that table?
Upvotes: 0