I have a function within NodeJS which is returning Json Javascript object.
let rows = function1();
Here rows look like:
"rows": [
{
"Hostname": "abc123",
"name": "name1",
"Status": "PASS",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc235",
"name": "name1",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc235",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
}
]
Here, rows can have any number of Json objects for the same Hostname key:
"rows": [
{
"Hostname": "abc123",
"name": "name1",
"Status": "PASS",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name3",
"Status": "FAIL",
"Heading": "Not Applicable"
},
...
{
"Hostname": "abc235",
"name": "name1",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc235",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc235",
"name": "name3",
"Status": "FAIL",
"Heading": "Not Applicable"
}
...
]
I want to modify the rows array such that all Javascript objects belonging to one Hostname are converted into a single Json object:
"rows": [
{
"Hostname": "abc123",
"name1Status": "PASS",
"name1Heading": "Not Applicable"
"name2Status": "FAIL",
"name2Heading": "Not Applicable"
"name3Status": "FAIL",
"name3Heading": "Not Applicable"
...
},
{
"Hostname": "abc235",
"name1Status": "FAIL",
"name1Heading": "Not Applicable"
"name2Status": "FAIL",
"name2Heading": "Not Applicable"
"name3Status": "FAIL",
"name3Heading": "Not Applicable"
...
}
]
I have written the following code but it overwrites all key value pairs and shows Json objects related to the last Hostname only
const res = rows.reduce((acc, rec) => {
let result = { ...acc, [`Hostname`]: rec.Hostname, [`${rec.name}Status`]: rec.Status, [`${rec.name}Heading`]: rec.Heading }
return result
}, [])
{
"Hostname": "abc235",
"name1Status": "FAIL",
"name1Heading": "Not Applicable"
"name2Status": "FAIL",
"name2Heading": "Not Applicable"
"name3Status": "FAIL",
"name3Heading": "Not Applicable"
}
There could be some form of for loop outside of res so that it takes into account all distinct Hostname keys
{ "Hostname": "abc235", "rows": [...] }, { "Hostname", "def234", "rows": [...] }would be much cleaner.name1Statusandname2Statusandname3Statusare hard for the consumer of this object to use. they would literally have to manufacture property names and see if they exist. Much better to offer an array of result objects that can be handled like any array of results.