JS中数组降维处理+数组对象中有相同键值对的合并重组成新对象元素

Posted 尔嵘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS中数组降维处理+数组对象中有相同键值对的合并重组成新对象元素相关的知识,希望对你有一定的参考价值。

数据源:

let arr1 = [
		 [
		  {pmax: 3.34, pmaxTime: "2021-08-30 20:14:32", deviceID: 900, dbtime: "2021-08"},
		  {pmax: 5.84, pmaxTime: "2021-08-30 20:33:21", deviceID: 901, dbtime: "2021-08"},
		  {pmax: 15.91, pmaxTime: "2021-08-25 23:49:40", deviceID: 903, dbtime: "2021-08"}
		 ],
		 [
		   {pmax: 3.46, pmaxTime: "2021-09-05 21:16:43", deviceID: 900, dbtime: "2021-09"},
		   {pmax: 6.09, pmaxTime: "2021-09-05 21:16:43", deviceID: 901, dbtime: "2021-09"},
		   {pmax: 16.15, pmaxTime: "2021-09-09 01:34:03", deviceID: 903, dbtime: "2021-09"}
		 ]
]

目标数据:

let arr1 = [
		 {
		  deviceID: 900,pmax0: 3.34, pmaxTime0: "2021-08-30 20:14:32",pmax1: 3.46, pmaxTime1: "2021-09-05 21:16:43"
		 },
		 {
		  deviceID: 901,pmax0: 5.84, pmaxTime0: "2021-08-30 20:33:21",pmax1: 6.09, pmaxTime1: "2021-09-05 21:16:43"
		 },
		 {
		  deviceID: 903,pmax0: 15.91, pmaxTime0: "2021-08-25 23:49:40",pmax1: 16.15, pmaxTime1: "2021-09-09 01:34:03"
		 }
]

实现过程:

let arrAll = []; //数组转换为一维数组
		let ids = {}; //存储id并储存相同id的数组
		let result = [];
		arrAll = arr1.flat();
		//    console.log(arrAll)
		arrAll.forEach(item => {
			if (ids[item.deviceID]) {
				ids[item.deviceID].push(item)
			} else {
				ids[item.deviceID] = [item]
			}
		})
		console.log(ids)
		let keys = Object.keys(ids);
		for (let i = 0; i < keys.length; i++) {
			let item = ids[keys[i]];
			let obj = {
				deviceID: keys[i]
			}
			for (let j = 0; j < item.length; j++) {
				obj[`pmax${j}`] = item[j].pmax
				obj[`pmaxTime${j}`] = item[j].pmaxTime
				obj[`dbtime${j}`] = item[j].dbtime
			}
			result.push(obj)
}
console.log(result)

以上是关于JS中数组降维处理+数组对象中有相同键值对的合并重组成新对象元素的主要内容,如果未能解决你的问题,请参考以下文章

js中往数组对象中添加键值对的方法有哪些?

html #JS您还可以将对象视为键值对的组合(如数组)//源http://jsbin.com/cuzaye/1

JS基础 Map是一组键值对的结构

Restkit 返回具有 0 个键值对的对象数组

华为机试:合并表记录

怎样从对象中获取键值并保存在对象中