[js] Merge array objects with the same key name

Preface:
During the process of the project, it was found that the data returned by the backstage was not in the same form as the required data
insert image description here
.
insert image description here

			function resetArr(arr) {
    
    
				// arrWarp 用于存放唯一键, result 最终返回数组
				let arrWarp = [],result = [];
				// 最终返回数组
				for (let item of arr) {
    
    
					if (!arrWarp.includes(item.attrName)) {
    
    
						let obj = {
    
    
							attrName: item.attrName,
							attrValueArr: []
							// classList 存放相同Id下的数据
						}
						obj.attrValueArr.push(item.attrValueArr);
						result.push(obj);
						arrWarp.push(item.attrName);
					} else {
    
    
					//如果跟arrWarp中有相同的内容,则选择相同的键名,插入到相同键名下的attrValueArr数组中
						result[arrWarp.indexOf(item.attrName)].attrValueArr.push(item.attrValueArr);
					};
				};
				return result;
			}


Reference: JavaScript merges the same value in array objects (array object merge)
But, from the above, we can see another problem, the same key name will appear in attrValueArr, so we need to judge whether there are duplicate values ​​when adding.
For details, see: Array deduplication, methods of adding non-repeating elements

Guess you like

Origin blog.csdn.net/liqiannan8023/article/details/130111661