¿Cómo aplanar la matriz anidada?
Oct 28 2020
¿Cómo aplano la matriz anidada en la matriz?
Aquí está la matriz de entrada de ejemplo,
const input = [
{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}, {
id: 4,
name: 'Charles',
otherFields: [{
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
}
]
Matriz de salida que quiero obtener.
[{
id: 1,
name: 'Charles'
}, {
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}, {
id: 4,
name: 'Charles'
}, {
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
Quiero de alguna manera obtener el resultado en una declaración como
input.map((sth) => ({...sth??, sth.field...})); // I'm not sure :(
Respuestas
4 CertainPerformance Oct 28 2020 at 00:22
Con flatMappuede eliminar la otherFieldspropiedad y devolver una matriz que contiene el elemento principal y la otra matriz:
const input = [{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}];
console.log(
input.flatMap(({ otherFields, ...item }) => [item, ...otherFields])
);
1 NinaScholz Oct 28 2020 at 00:39
Para más de un nivel, puede adoptar un enfoque recursivo de aplanamiento.
const
flat = ({ otherFields = [], ...o }) => [o, ...otherFields.flatMap(flat)],
input = [{ id: 1, name: 'Charles', otherFields: [{ id: 2, name: 'Pung' }, { id: 3, name: 'James', otherFields: [{ id: 4, name: 'Jane' }] }] }],
result = input.flatMap(flat);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }