js 把数组的多个对象合并成一个对象,key相同的,把value合并成数组,怎么做?
//原数据
list = [
{
brand: "Hisense1",
name: "C Series",
type: "多联机和新风机通用室外机",
photo: "",
minRatio: 0.5,
maxRatio: 1.3,
alarmMaxRatio: 0,
isOnmarket: true,
isDefault: false,
DWGFile: "",
pictureFile: "",
remarks: "",
id: "b53d408d-c4f9-4751-86a0-37751c48c6ad",
},
{
brand: "Hisense2",
name: "C Series",
type: "多联机和新风机通用室外机",
photo: "",
minRatio: 0.5,
maxRatio: 1.3,
alarmMaxRatio: 0,
isOnmarket: true,
isDefault: false,
DWGFile: "",
pictureFile: "",
remarks: "",
id: "b53d408d-c4f9-4751-86a0-37751c48c6ad",
},
//想要的数据
listFilters =
{
brand: ["Hisense1", "Hisense2"],
name: ["C Series", "B Series"],
type: ["多联机和新风机通用室外机1", "多联机和新风机通用室外机2"],
...
}
因为我想要的数据结构有点变化:
listFilters =
{
brand: [{text:"Hisense1",value:"Hisense1"}, {text:"Hisense2",value:"Hisense2"}],
...
}
最后我用的方法是:
for (let i = 0; i < this.list.length; i++) {
for (let key in this.list[i]) {
if (this.listFilters.hasOwnProperty(key)) {
//如果已经有属性名称,则追加值
let flag = false;
for (let j = 0; j < this.listFilters[key].length; j++) {
if (this.listFilters[key][j].value === this.list[i][key]) {
flag = true;
}
}
if (!flag) {
//如果属性值不相同时追加
this.listFilters[key].push({
text: this.list[i][key],
value: this.list[i][key],
});
}
} else {
//如果没有属性名称则添加key:value
this.listFilters[key] = [
{ text: this.list[i][key], value: this.list[i][key] },
];
}
}
}
Array.prototype.reduce
是个好东西:直接看代码:
每一步的说明:
数组与对象之间进行相互转换的过程中,
Array.prototype.reduce
用好了,事半功倍,不要说这样的代码难看懂,如果思维清楚,这样的代码从头看到尾应该是很容易知道运行结果的。运行结果: