功能介绍:在一个数组内根据多个条件进行合并并生成指定的子数组。
数组数据:
var data = [ {"id": "7612", "name": "张三", "age": 23, "type": 1, "area": "本院", date: "2023-03-08 16:30:00"}, {"id": "7612", "name": "张三", "age": 23, "type": 2, "area": "西红柿院区", date: "2023-03-08 17:00:00"}, {"id": "7614", "name": "张王武", "age": 23, "type": 2, "area": "西红柿院区", date: "2023-03-08 17:00:00"}, {"id": "7617", "name": "里斯", "age": 23, "type": 1, "area": "西红柿院区", date: "2023-03-08 14:30:00"}, {"id": "7617", "name": "里斯", "age": 23, "type": 2, "area": "本院", date: "2023-03-08 15:00:00"} ]
封装方法:
function handlerLogsData(arr){ let tempArr = []; let resultData = []; for (let i = 0; i < arr.length; i++) { let _logs = [] if (tempArr.indexOf(arr[i].name) == -1 && 根据name一样加条件) == -1) { _logs.push({ type: arr[i].type, area: arr[i].area, date: arr[i].date }) resultData.push({ name: arr[i].name, id: arr[i].id, age: arr[i].age, logs: _logs }); tempArr.push(arr[i].name); } else { for (let j = 0; j < resultData.length; j++) { if (resultData[j].name == arr[i].name && resultData[j].id == arr[i].id) { resultData[j].logs.push({ type: arr[i].type, area: arr[i].area, date: arr[i].date }); break; } } } } return resultData }
调用方法:
console.log('输出结果:', handlerLogsData(data)) 输出结果: [ { "name": "张三", "id": "7612", "age": 23, "logs": [ { "type": 1, "area": "本院", "date": "2023-03-08 16:30:00" }, { "type": 2, "area": "西红柿院区", "date": "2023-03-08 17:00:00" } ] }, { "name": "张王武", "id": "7614", "age": 23, "logs": [ { "type": 2, "area": "西红柿院区", "date": "2023-03-08 17:00:00" } ] }, { "name": "里斯", "id": "7617", "age": 23, "logs": [ { "type": 1, "area": "西红柿院区", "date": "2023-03-08 14:30:00" }, { "type": 2, "area": "本院", "date": "2023-03-08 15:00:00" } ] } ]
javascript语法如何把json文件输出到html页面上
标签: j数组合并
上面是“js数组内多条件合并,生成子数组”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_3807.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!