我怎样才能 "unpack" 一个嵌套对象作为一个数组?
How can I "unpack" a nested object as an array?
我有一个由可迭代项组成的对象(键只是日期字符串)。其中一些对象不止一项。
我想展平每个对象,以便只保留一维对象。
基本上,我希望 data
看起来像 expected
:
const data = {
//this datestring only has one item
"1598989834745": {
"219319571 ": {
applicantCode: "goc2gp",
carrera: "Trabajo Social",
code: "219319571 "
}
},
//this one has two items
"1598990166911": {
"215576855": {
applicantCode: "8e11532",
carrera: "Médico Cirujano y Partero",
code: "215576855"
},
"217831836": {
applicantCode: "ybg14pd",
carrera: "Trabajo Social",
code: "217831836"
}
}
};
const expected = [
{
applicantCode: "goc2gp",
carrera: "Trabajo Social",
code: "219319571 "
},
{
applicantCode: "8e11532",
carrera: "Médico Cirujano y Partero",
code: "215576855"
},
{
applicantCode: "ybg14pd",
carrera: "Trabajo Social",
code: "217831836"
}
];
我试过映射 Object.keys
:
function objToArr(obj: object): object[] {
return Object.keys(obj).map(key => obj[key]);
}
但是当我不止一次这样做(覆盖两个维度)时,它 returns 这个:
[
{
'219319571 ': {
applicantCode: 'goc2gp',
carrera: 'Trabajo Social',
code: '219319571 '
}
},
{
'215576855': {
applicantCode: '8e11532',
carrera: 'Médico Cirujano y Partero',
code: '215576855'
},
'217831836': {
applicantCode: 'ybg14pd',
carrera: 'Trabajo Social',
code: '217831836'
}
}
]
```
您可以通过几个 Object.values 电话到达那里。沿着这些线的东西:
const expected = Object.values(data).map(v => Object.values(v)).flat()
我有一个由可迭代项组成的对象(键只是日期字符串)。其中一些对象不止一项。
我想展平每个对象,以便只保留一维对象。
基本上,我希望 data
看起来像 expected
:
const data = {
//this datestring only has one item
"1598989834745": {
"219319571 ": {
applicantCode: "goc2gp",
carrera: "Trabajo Social",
code: "219319571 "
}
},
//this one has two items
"1598990166911": {
"215576855": {
applicantCode: "8e11532",
carrera: "Médico Cirujano y Partero",
code: "215576855"
},
"217831836": {
applicantCode: "ybg14pd",
carrera: "Trabajo Social",
code: "217831836"
}
}
};
const expected = [
{
applicantCode: "goc2gp",
carrera: "Trabajo Social",
code: "219319571 "
},
{
applicantCode: "8e11532",
carrera: "Médico Cirujano y Partero",
code: "215576855"
},
{
applicantCode: "ybg14pd",
carrera: "Trabajo Social",
code: "217831836"
}
];
我试过映射 Object.keys
:
function objToArr(obj: object): object[] {
return Object.keys(obj).map(key => obj[key]);
}
但是当我不止一次这样做(覆盖两个维度)时,它 returns 这个:
[
{
'219319571 ': {
applicantCode: 'goc2gp',
carrera: 'Trabajo Social',
code: '219319571 '
}
},
{
'215576855': {
applicantCode: '8e11532',
carrera: 'Médico Cirujano y Partero',
code: '215576855'
},
'217831836': {
applicantCode: 'ybg14pd',
carrera: 'Trabajo Social',
code: '217831836'
}
}
]
```
您可以通过几个 Object.values 电话到达那里。沿着这些线的东西:
const expected = Object.values(data).map(v => Object.values(v)).flat()