tengo una matriz como
Const array=[ { id:1, name:"abc", Address:[ { City: "something", Country: "first country" }, { City: "other city", Country: "country" } ] }, { ........... } ];Tengo que mostrar esta matriz de objetos anidados como una lista de valores de clave plana. Entonces, ¿cómo reducir esto como a continuación?
Reducedarray = [ { Id: 1, name: "abc" }, { City: "something", country: "first country"}, { City: "other city", country: "country"}, { Id: 2, name: "bbc" }, { City: "bbcsomething", country: "fbbct country"}, { City: "other city", country: "country"} ]Usando reducearray, mapearé con claves de objeto y mostraré como lista de valores clave en html.
Necesita mostrarse como una lista plana usando jsx como a continuación
Id: 1 Nombre: abc Ciudad: primera ciudad País: primer país Ciudad: segunda ciudad País: segundo país Id: 2 Nombre: otro nombre ..... ...... ....
¿Alguien puede ayudarme con esto, por favor? ¿Es posible solo con reducir?
Puede tomar un mapa plano con el objeto de descanso desestructurado y la matriz de Address .
const array = [{ id: 1, name: "abc", Address: [{ City: "something", Country: "first country" }, { City: "other city", Country: "country" }] }], result = array.flatMap(({ Address, ...o }) => [o, ...Address]); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }Solución con reducir:
const data = [{ id: 1, name: "abc", Address: [{ City: "something", Country: "first country" }, { City: "other city", Country: "country" }] }, { id: 2, name: "dfe", Address: [{ City: "something1", Country: "second country" }, { City: "city", Country: "new country" }] }]; const Reducedarray = data.reduce((acc, { Address, ...rest }) => ( [...acc, rest, ...Address] ), []); console.log(Reducedarray ); .as-console-wrapper { max-height: 100% !important; top: 0; }const array= [ { id:1, name:"abc", Address:[ { City: "something", Country: "first country" }, { City: "other city", Country: "country" } ] }, ]; const array2 = [] for(let el of array) { if(el.id) array2.push({id: el.id, name: el.name}) if(el.Address) { for(let element of el.Address) { array2.push({ city: element.City, country: element.Country}) } } } console.log(array2)