我已从已转换为以下数据库的数据库中检索数据:
"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": ""
}
]
}
他使用lodash获得的
let grouped = groupBy(results, function (result) {
return result.nameSection;
})
我的结果是来自数据库的原始数据。 我注意到lodash将我的“ nameSection”设置为JSON中的键,但是我不知道如何才能获得理想的效果。 我正在尝试使用.map()(对吗?)以获得此结果:
"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": ""
}
]
}
对于解决问题的帮助和提示,我将不胜感激。
答案 0 :(得分:1)
使用nameSection
键和data
数组将对象的条目映射到对象,同时覆盖数组中每个对象的nameSection
属性:
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);