将数组里某个属性相同的对象合并成一个数组
原数组如下
let resData = [
{
"name": "住院医疗最高报销",
"tagName": "医疗",
"insuredAmount": "6000"
},
{
"name": "身故赔付",
"tagName": "寿险",
"insuredAmount": "36.00"
},
{
"name": "烦死了免费陈述事实",
"tagName": "寿险",
"insuredAmount": "8888.00"
},
{
"name": "你好,噜噜噜",
"tagName": "寿险",
"insuredAmount": "66.00"
},
{
"name": "120种重大疾病确诊赔付",
"tagName": "重疾",
"insuredAmount": "350000"
}
]
需求是,转成如下数组
也就是将具有相同“tagName”的对象合并成新数组
let Data = [
{
"tagName": "医疗",
dataInfo: [
{
"name": "住院医疗最高报销",
"tagName": "医疗",
"insuredAmount": "6000"
}
]
},
{
"tagName": "寿险",
dataInfo: [
{
"name": "身故赔付",
"tagName": "寿险",
"insuredAmount": "36.00"
},
{
"name": "烦死了免费陈述事实",
"tagName": "寿险",
"insuredAmount": "8888.00"
},
{
"name": "你好,噜噜噜",
"tagName": "寿险",
"insuredAmount": "66.00"
},
]
},
{
"tagName": "重疾",
dataInfo: [
{
"name": "120种重大疾病确诊赔付",
"tagName": "重疾",
"insuredAmount": "350000"
}
]
}
]
以下是解决方案
方案一:
let tempArr = [];
let Data = [];
for (let i = 0; i < resData.length; i++) {
if (tempArr.indexOf(resData[i].tagName) === -1) {
Data.push({
tagName: resData[i].tagName,
dataInfo: [resData[i]]
});
tempArr.push(resData[i].tagName);
} else {
for (let j = 0; j < Data.length; j++) {
if (Data[j].tagName == resData[i].tagName) {
Data[j].dataInfo.push(resData[i]);
break;
}
}
}
}
console.log(Data);
方案二:
let dataInfo = {};
resData.forEach((item, index) => {
let { tagName } = item;
if (!dataInfo[tagName]) {
dataInfo[tagName] = {
tagName,
child: []
}
}
dataInfo[tagName].child.push(item);
});
let list = Object.values(dataInfo); // list 转换成功的数据
console.log(list)
以上方法综合借鉴了其他博主的文章,总结以供大家一起学习!
转自于:https://blog.csdn.net/shiningyn/article/details/105409636