0

quiero trasnformar un array de objetos a un objeto que contenga sus llaves. Les muestro con un ejemplo

Tengo el siguiente array:

const dataSource = [
{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
{ position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
{ position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
{ position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
{ position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
{ position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
{ position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
{ position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

y quiero transformarlo en algo asi:

const dataSource = {
   position: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
   name: ['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen','Oxygen', 'Fluorine', 'Neon'],
   weight: [1.0079, 4.0026, 6.941, 9.0122, 10.811, 12.0107, 14.0067, 15.9994, 18.9984, 20.1797],
   symbol: ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'],
};

2 respuestas 2

2

La idea es la siguiente:

  1. Creas un objeto vacío output donde guardarás tus arrays por claves.
  2. Por cada elemento de tu array original, iteras en sus claves.
  3. Si la clave no existe en tu objeto de salida, la creas en ese momento en forma de arreglo.
  4. Si la clave existe, simplemente agregas el elemento actual al arreglo.

Un ejemplo con .foreach sería:

const dataSource = [
    { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
    { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
    { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
    { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
    { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
    { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
    { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
    { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
    { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
    { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

let output = {}
dataSource.forEach(data => {
    Object.keys(data).forEach(key => {
        if (output.hasOwnProperty(key))
            output[key].push(data[key])
        else
            output[key] = [data[key]]
    })
})

console.log(output)

2
  • 1
    Gracias !!!!!!! el 7 mar. 2022 a las 20:09
  • 1
    Elegante solución
    – Edgar Gc
    el 7 mar. 2022 a las 20:13
1

Se me ocurre que uses Array.prototype.map() por cada item que deseas obtener, algo como esto:

const dataSource = [
    { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
    { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
    { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
    { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
    { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
    { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
    { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
    { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
    { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
    { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];

const mapIds = dataSource.map(item => item.position )
const mapNames = dataSource.map(item => item.name )
const mapWeight = dataSource.map(item => item.weight )
const mapSymbol = dataSource.map(item => item.symbol )

console.log([mapIds, mapNames, mapWeight, mapSymbol])

2
  • Estoy buscando en lo posible que sea escalable. No siempre van a ser "position", "name", "weight" o "symbol" el 7 mar. 2022 a las 20:04
  • ¿Tu json siempre va a cambiar? Es decir, ¿tendrá un formato diferente cada que envíes algo nuevo?
    – Edgar Gc
    el 7 mar. 2022 a las 20:07

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.