将对象拆分为对象数组



我想在键中按年份将下面的对象分为两个对象。后端响应为a.

const a = {
"id": "2",
"2019_progrSin": "2",
"2019_percResponsabilita": "30",
"2019_flag": "B",
"2019_tipoResponsabilitaSinistro": "O",
"2019_anno": "2019",
"2019_codComp": "O",
"2018_progrSin": "2",
"2018_percResponsabilita": "50",
"2018_flag": "Y",
"2018_tipoResponsabilitaSinistro": "I",
"2018_anno": "2018",
"2018_codComp": "O"
}

要在我的表中显示a,我想从a获得b,比如:

const b = [
{
"2019_progrSin": "2",
"2019_percResponsabilita": "30",
"2019_flag": "B",
"2019_tipoResponsabilitaSinistro": "O",
"2019_anno": "2019",
"2019_codComp": "O",
},
{
"2018_progrSin": "2",
"2018_percResponsabilita": "50",
"2018_flag": "Y",
"2018_tipoResponsabilitaSinistro": "I",
"2018_anno": "2018",
"2018_codComp": "O"
}
]

属性可以更多。(如"2017_flag"/"2016_flag(

使用Array.prototype.reduce、Object.values和Object.entries

const input = {
id: "2",
"2019_progrSin": "2",
"2019_percResponsabilita": "30",
"2019_flag": "B",
"2019_tipoResponsabilitaSinistro": "O",
"2019_anno": "2019",
"2019_codComp": "O",
"2018_progrSin": "2",
"2018_percResponsabilita": "50",
"2018_flag": "Y",
"2018_tipoResponsabilitaSinistro": "I",
"2018_anno": "2018",
"2018_codComp": "O",
};
const output = Object.values(
Object.entries(input).reduce((prev, [key, value]) => {
const [year] = key.split("_");
if (!isNaN(year)) {
if (!prev[year]) {
prev[year] = {};
}
prev[year][key] = value;
}
return prev;
}, {})
);
console.log(output);

您可以实现对所有项目的解析,如下所示:

const yearObj = {}
let results = []
for (const [key, value] of Object.entries(obj)) {
if(key != "id") {
const year = key.split('_')[0]
if(!yearObj[year]) yearObj[year] = {}
yearObj[year][key] = value
}
}
for (const value of Object.values(yearObj)) {
results.push(value)
}

这可能更具体,使用正则表达式解析对象的键,只得到4位数的

最新更新