js数组内多条件合并,生成子数组

437 ℃

功能介绍:在一个数组内根据多个条件进行合并并生成指定的子数组。

数组数据:

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"
      }
    ]
  }
]

js用最简单的方法实现2个数组的交叉一对一合并

如何利用js语法将2个数组进行交叉合并

利用js语法把数组根据相同key转换成嵌套数组格式

javascript语法如何把json文件输出到html页面上

js点击按钮从服务器上下载json文件(不是打开文件)

标签: j数组合并

上面是“js数组内多条件合并,生成子数组”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://m.ipkd.cn/webs_3807.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

js如何获取x的绝对值
php语法如何查询数据库转数组输出
Layui - Vue 前端UI框架的调用
Go语言开发中出现的常见错误有哪些?
如何利用uni-app获取微信步数(附代码)