En mi ejemplo, tengo una matriz de objetos que quiero asignar a otra matriz de objetos:
Resurs.map((item) => ({ Cen: item.Cent, level: [ item.NumList.map((item) => ({ Kom: item.Number, Num: item.Kor, })), item.SerList.map((item) => ({ Kom2: item.Ser, })), ], }));Entonces, tengo 2 métodos de mapa dentro del método de mapa. Volverá:
{ Cen: "aaa", level: [ [ // -> want to get rid of this { Kom: "aaa", Num: "aaa", }, { Kom: "bbb", Num: "bbb", }, ], // -> and this [ //-> and this { Kom2: "aaa" }, { Kom2: "bbb" }, ], //-> and this ], }; Por lo tanto, ambas funciones de mapa deben estar dentro de la clave de level , pero no como una lista que tiene dos listas dentro, sino como una lista con objetos.
Entonces, quiero lograr:
{ Cen: "aaa", level: [ { Kom: "aaa", Num: "aaa", }, { Kom: "bbb", Num: "bbb", }, { Kom2: "aaa" }, { Kom2: "bbb" }, ], };¡Ya casi has llegado! La respuesta es operador de propagación. Simplemente insértelo en su mapa interno.
Puede usar un operador de extensión para expandir las matrices cuando inserta en el nivel.
El operador de propagación se puede utilizar con una matriz o un objeto.
Ejemplo:
var a = [1, 2, 3, 4]; var b = [5, 6, 7]; var c = [a, b]; // [[1, 2, 3, 4], [5, 6, 7]] // This is what you are doing Solution: var d = [...a, ...b]; // [1, 2, 3, 4, 5, 6, 7]Solución completa:
const Resurs = [ { Cent: "centValue", NumList: [ { Number: "numValue1", Kor: "KorValue1" }, { Number: "numValue3", Kor: "KorValue2" }, { Number: "numValue3", Kor: "KorValue3" } ], SerList: [ { Ser: "SerValue1" }, { Ser: "SerValue2" } ] } ]; const data = Resurs.map((item) => ({ Cen: item.Cent, level: [ ...item.NumList.map((item) => ({ // Just add ... Kom: item.Number, Num: item.Kor, })), ...item.SerList.map((item) => ({ // Just add ... Kom2: item.Ser, })), ], })); console.log(data);No cree la matriz externa en primer lugar:
const data = Resurs.map((item) => ({ Cen: item.Cent, level: item.NumList.map((item) => ({ Kom: item.Number, Num: item.Kor, })).concat(item.SerList.map((item) => ({ Kom2: item.Ser, }))), }));