JS数组格式转换的问题
服务器返回大量数据,格式大概是这样的。{
count: 8,
id: {responsibleRegion: "市公司", responsibleGrid: "生产室", responsibleName: "唐生", workType: "核查资源", isComplete: false}
},{
count: 7,
id: {responsibleRegion: "茂南 ", responsibleGrid: "城东", responsibleName: "李生", workType: "弱光整治", isComplete: false}
},{
count: 16,
id: {responsibleRegion: "高州", responsibleGrid: "城西", responsibleName: "梁生", workType: "弱光整治", isComplete: true}
}
先说明一下数据,数据的层级关系是这样的:workType→responsibleRegion→responsibleGrid→responsibleName,即工作类型→区域→网格→个人。
count是数量,isComplete通过true或false确定是isComplete或notComplete。
我希望统计出各层级的情况,通过item承载下一级,如[{name: "核查资源",isComplete: 88,notComplete: 66,item:[...],...]。
将数据转换成大概这样:
[
{name: "核查资源",isComplete: 88,notComplete: 66,item: [{name: "茂南",isComplete: 38,notComplete: 36,item: [{name: "城东",isComplete: 28,notComplete: 26,item:}]}]},
...
]
我知道要for循环,但情况比较复杂,搞了半天没想明白怎么搞,求指点。
json数据啊,用JSON来解 艹,这嵌套太复杂了,写不下去了。
数据结构大概是这样,首次写入,第二次就不知道怎么写了。请指教。
//循环统计数据
const DATA_ALL = THIS_RES.all
var count_All = []
var listType = []
for (let i = 0; i < DATA_ALL.length; i++) {
if (!listType.includes(DATA_ALL._id.workType)) {
listType.push(DATA_ALL._id.workType)
let isComplete = 0
let notComplete = 0
let allNum = DATA_ALL.count
if (DATA_ALL._id.isComplete) {
isComplete = DATA_ALL.count
} else {
isComplete = DATA_ALL.count
}
count_All._id.workType)] = {
name: DATA_ALL._id.workType,
isComplete,
notComplete,
allNum,
item: [{
name: DATA_ALL._id.responsibleRegion,
isComplete,
notComplete,
allNum,
item: [{
name: DATA_ALL._id.responsibleGrid,
isComplete,
notComplete,
allNum,
item: [{
name: DATA_ALL._id.responsibleName,
isComplete,
notComplete,
allNum
}]
}]
}]
}
}
// console.log(DATA_ALL._id.workType)
// console.log(DATA_ALL._id.responsibleRegion)
// console.log(DATA_ALL._id.responsibleGrid)
// console.log(DATA_ALL._id.responsibleName)
// console.log(DATA_ALL.count)
} 搜索一下 js for...in 建议按照 工作类型→区域→网格→个人这个层级关系,最外层一个大的对象存储,里面每层一个对象存储下一层的数据依次嵌套。 alterempty 发表于 2021-4-12 21:20
搜索一下 js for...in
for in我了解,但还是没想到怎么实现,给个思路,谢谢。 map filter reduce foreach + 箭头函数 这不对啊,数据源有问题,这不是json,除非你把key提前定义好了 来源是三条 json,拼一下格式化:
{
"source": [
{
"count": 8,
"id": {
"responsibleRegion": "市公司",
"responsibleGrid": "生产室",
"responsibleName": "唐生",
"workType": "核查资源",
"isComplete": false
}
},
{
"count": 7,
"id": {
"responsibleRegion": "茂南 ",
"responsibleGrid": "城东",
"responsibleName": "李生",
"workType": "弱光整治",
"isComplete": false
}
},
{
"count": 16,
"id": {
"responsibleRegion": "高州",
"responsibleGrid": "城西",
"responsibleName": "梁生",
"workType": "弱光整治",
"isComplete": true
}
}
]
}
你要的结果拼一下格式化:
{
"result": [
{
"name": "核查资源",
"isComplete": 88,
"notComplete": 66,
"item": [
{
"name": "茂南",
"isComplete": 38,
"notComplete": 36,
"item": [
{
"name": "城东",
"isComplete": 28,
"notComplete": 26,
"item": [
{
"name": "李生",
"isComplete": 8,
"notComplete": 6
}
]
}
]
}
]
}
]
}
就是解析Json取节点再组织json输出的事情 sail2000 发表于 2021-4-13 10:27
来源是三条 json,拼一下格式化:
{
"source": [
JS 实现哦,有JS代码吗?谢谢
页:
[1]
2