Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
En un objeto que anida pares clave-valor, ¿cómo convertir una matriz de un solo valor en solo el valor en sí?

Dada una matriz que anida objetos internos que tienen pares clave-valor, quiero convertir matrices de un solo elemento en solo el valor en sí.

Así que digamos que tenemos la siguiente matriz de albums :

 const albums = [ { "band": ["beetles"], "album": ["yellow_submarine"], "year": [1969] }, { "band": [ "coldplay"], "album": ["Parachutes"], "year": [2000] }, { "band": ["nirvana"], "album": ["nevermind"], "year": [1991] } ]

Dado que todas las matrices son valores únicos, me gustaría convertir este objeto de albums completo a:

 // desired output [ { "band": "beetles", "album": "yellow_submarine", "year": 1969 }, { "band": "coldplay", "album": "Parachutes", "year": 2000 }, { "band": "nirvana", "album": "nevermind", "year": 1991 } ]

Parece que hay muchas publicaciones que discuten lo contrario (es decir, cómo convertir un valor único en una matriz), pero no pude encontrar una respuesta a esta pregunta actual. Tal vez no estoy usando los términos de búsqueda correctos...

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Asigne albums a una nueva matriz de objetos, use un método unArray dentro del map -lambda

 const albums = [{ "band": ["beetles"], "album": ["yellow_submarine"], "year": [1969] }, { "band": ["coldplay"], "album": ["Parachutes"], "year": [2000] }, { "band": ["nirvana"], "album": ["nevermind"], "year": [1991] } ]; // Note: for a true copy of albums and its arrays, // the values must be spreaded (eg ...album.band) const noArrays = albums.map(album => { const unArray = v => v.length === 1 ? v.shift() : v; return { ...{}, band: unArray(...album.band), album: unArray(...album.album), year: unArray(...album.year) }; }); console.log(noArrays);
 .as-console-wrapper { max-height: 100% !important; }

Si no se conocen (todas) las claves de las entradas de los albums , sería más genérico usar un reductor para todas las entradas de los album :

 const albums = [{ "band": ["beetles"], "album": ["yellow_submarine"], "year": [1969] }, { "band": ["coldplay"], "album": ["Parachutes"], "year": [2000] }, { "band": ["nirvana"], "album": ["nevermind"], "year": [1991] } ]; // Note: for a true copy of albums and its arrays, // the values ust be spreaded (ie ...value) const noArrays = albums.map( album => { const unArray = v => v.length === 1 ? v.shift() : v; return Object.entries(album).reduce( (acc, [key, value]) => ({...acc, [key]: unArray(...value)}), {}); }); console.log(noArrays);

about 4 years ago · Juan Pablo Isaza Report

0

Si desea crear una nueva matriz de nuevos objetos, usaría el map junto con la creación de nuevos objetos que desenvuelven sus valores. Tiene un par de opciones sobre cómo manejar los objetos. Podrías usar Object.fromEntries y Object.entries :

 const updatedAlbums = albums.map(album => Object.fromEntries( Object.entries(album).map(([key, value]) => [key, value[0]]) ) );

Ejemplo en vivo:

 const albums = [ { "band": ["beetles"], "album": ["yellow_submarine"], "year": [1969] }, { "band": [ "coldplay"], "album": ["Parachutes"], "year": [2000] }, { "band": ["nirvana"], "album": ["nevermind"], "year": [1991] } ]; const updatedAlbums = albums.map(album => Object.fromEntries( Object.entries(album).map(([key, value]) => [key, value[0]]) ) ); console.log(updatedAlbums);
 .as-console-wrapper { max-height: 100% !important; }

O podría usar un bucle interno para evitar matrices intermedias:

 const updatedAlbums = albums.map(album => { const newAlbum = {}; for (const key in album) { if (Object.hasOwn(album, key)) { newAlbum[key] = album[key][0]; // Unwrapping the value } } return newAlbum; });

Ejemplo en vivo:

 const albums = [ { "band": ["beetles"], "album": ["yellow_submarine"], "year": [1969] }, { "band": [ "coldplay"], "album": ["Parachutes"], "year": [2000] }, { "band": ["nirvana"], "album": ["nevermind"], "year": [1991] } ]; // Quick-and-dirty polyfill for environments that don't have `Object.hasOwn` yet if (!Object.hasOwn) { Object.hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); } const updatedAlbums = albums.map(album => { const newAlbum = {}; for (const key in album) { if (Object.hasOwn(album, key)) { newAlbum[key] = album[key][0]; // Unwrapping the value } } return newAlbum; }); console.log(updatedAlbums);
 .as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report

0

Editar: esto cambia el valor en lugar de crear un nuevo diccionario con el resultado final.

 for (var i = 0; i < albums.length; i++) { for (var key in albums[i]) { albums[i][key] = albums[i][key][0]; } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!