Reputation: 35
I have data retrieved from a database that I have transformed into:
"items": {
"title - nameSection": [
{
"nameBoard": "xxx",
"idTask": 1,
"nameTask": "xxx",
"contentTask": "xxx",
"complete": 1,
"idSection": 1,
"nameSection": "xxx",
"contentSection": "xxx"
},
{
"nameBoard": "xxx",
"idTask": 2,
"nameTask": "xxx",
"contentTask": "xxx",
"complete": 1,
"idSection": 1,
"nameSection": "xxx",
"contentSection": ""
}
],
"title 2 - nameSection": [
{
"nameBoard": "xxx",
"idTask": 3,
"nameTask": "xxx",
"contentTask": "",
"complete": 0,
"idSection": 2,
"nameSection": "xxx",
"contentSection": ""
}
]
}
which he obtained by using lodash:
let grouped = groupBy(results, function (result) {
return result.nameSection;
})
My results are raw data from a database. I noticed that lodash sets my 'nameSection' as a key in JSON however I don't know how I could get the desired effect. I'm trying with .map() (right?) To get this result:
"items": {
"nameSection": "title - nameSection",
"data": [
{
"nameBoard": "xxx",
"idTask": 1,
"nameTask": "xxx",
"contentTask": "xxx",
"complete": 1,
"idSection": 1,
"nameSection": "title - nameSection",
"contentSection": "xxx"
},
{
"nameBoard": "xxx",
"idTask": 2,
"nameTask": "xxx",
"contentTask": "xxx",
"complete": 1,
"idSection": 1,
"nameSection": "title - nameSection",
"contentSection": ""
}
],
"nameSection": "title2 - nameSection",
"data": [
{
"nameBoard": "xxx",
"idTask": 3,
"nameTask": "xxx",
"contentTask": "",
"complete": 0,
"idSection": 2,
"nameSection": "title 2 - nameSection",
"contentSection": ""
}
]
}
I will be grateful for any help and tips on how to solve the problem.
Upvotes: 2
Views: 46
Reputation: 371168
Map the object's entries to an object with a nameSection
key and a data
array, while overwriting the nameSection
property in each object in the array:
const items={"title - nameSection":[{nameBoard:"xxx",idTask:1,nameTask:"xxx",contentTask:"xxx",complete:1,idSection:1,nameSection:"xxx",contentSection:"xxx"},{nameBoard:"xxx",idTask:2,nameTask:"xxx",contentTask:"xxx",complete:1,idSection:1,nameSection:"xxx",contentSection:""}],"title 2 - nameSection":[{nameBoard:"xxx",idTask:3,nameTask:"xxx",contentTask:"",complete:0,idSection:2,nameSection:"xxx",contentSection:""}]};
const output = Object.entries(items)
.map(([ nameSection, origData ]) => ({
nameSection,
data: origData.map(obj => ({ ...obj, nameSection }))
}))
console.log(output);
Upvotes: 1