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

154
Views
¿Cómo convierto un objeto en múltiples objetos dependiendo de cuántas teclas hay?

Tengo una pregunta sencilla .

Quiero convertir esta matriz de un objeto ...

 [ { id: 1, caseId: "Default Case Set", casenbr: "CASEWORK", submitterCasenbr: 34, othref: 0, sta: 0, type: 0, create: 0, startd: 0 } ]

en una matriz de múltiples objetos como este...

 [ { id: 1 }, { caseId: "Default Case Set" }, { casenbr: "CASEWORK" }, { submitterCasenbr: 34 }, { othref: 0 }, { sta: 0 }, { type: 0 }, { create: 0 }, { startd: 0 } ]

¿Cuál sería el mejor enfoque para hacer esto? Básicamente, quiero tomar todos los pares clave/valor en el objeto y convertirlos en objetos.

Entonces, si tengo una matriz de un objeto con 100 pares clave/valor, me gustaría crear una matriz de 100 objetos que tengan solo un par clave/valor.

La razón por la que hago esto es para crear una matriz que pueda usar para una directiva ngFor en mi aplicación Angular 13.

No sé si hay una forma de que ngFor en Angular se repita sobre los pares clave/valor de un objeto en una matriz, así que eso es lo que estoy creando en una matriz de varios objetos.

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

0

No creo que esta pregunta deba haberse cerrado ya que la respuesta está más en línea con cómo usar ngFor.

Si desea recorrer, digamos, su matriz, pero luego recorrer todas sus claves como columnas, podría tener algo como esto:

 <table> <thead> <tr> <th *ngFor="let column of data[0] | keyvalue"> {{ column.key }} </th> </tr> </thead> <tbody> <tr *ngFor="let row of data"> <td *ngFor="let column of row | keyvalue"> {{ column.value }} </td> </tr> </tbody> </table>

Esto le daría una tabla (junto con los encabezados) que imita sus datos. Vea este stackblitz: https://stackblitz.com/edit/angular-daubr3?file=src%2Fapp%2Fapp.component.html

about 4 years ago · Juan Pablo Isaza Report

0

Para lograr esto en JavaScript directamente, puede usar el método estático Object.entries() para deconstruir cada clave y valor y luego reconstruirlos con Object.fromEntries() como nuevos elementos de matriz.

 // Original Array with object const array = [ { id: 1, caseId: "Default Case Set", casenbr: "CASEWORK", submitterCasenbr: 34, othref: 0, sta: 0, type: 0, create: 0, startd: 0, }, ]; // Create an array of entries from the object const [entries] = array.map((el) => Object.entries(el)); console.log(entries); /* entries OUTPUT: [ [ 'id', 1 ], [ 'caseId', 'Default Case Set' ], [ 'casenbr', 'CASEWORK' ], [ 'submitterCasenbr', 34 ], [ 'othref', 0 ], [ 'sta', 0 ], [ 'type', 0 ], [ 'create', 0 ], [ 'startd', 0 ] ] */ // Create new array of Objects from entries const newArray = entries.map((entry) => Object.fromEntries([entry])); console.log(newArray); /* newArray OUTPUT: [ { id: 1 }, { caseId: 'Default Case Set' }, { casenbr: 'CASEWORK' }, { submitterCasenbr: 34 }, { othref: 0 }, { sta: 0 }, { type: 0 }, { create: 0 }, { startd: 0 } ] */
about 4 years ago · Juan Pablo Isaza Report

0

 console.log([{ id: 1, caseId: "Default Case Set", casenbr: "CASEWORK", submitterCasenbr: 34, othref: 0, sta: 0, type: 0, create: 0, startd: 0 }].reduce((acc, obj) => { Object.keys(obj).forEach((key) => { acc.push({[key]: obj[key]}) }); return acc; }, []));

Aquí hay una forma de hacerlo. Mediante el uso de una combinación de Array.reduce y Object.keys. Tenga en cuenta que si tiene varios objetos en su matriz raíz, iterará sobre ellos también y construirá objetos y los acumulará en la matriz de salida final también. Sin embargo, sus datos de ejemplo solo muestran 1 objeto en su matriz raíz.

Como han mencionado otros, nos falta el contexto que, en última instancia, informaría la mejor manera de ayudar a resolver el problema. Pero este código debería lograr lo que pretende hacer.

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!