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

354
Views
Cómo convertir una matriz en un objeto JavaScript

Tengo una matriz como esta (que es similar a una matriz JSON) de longitud n:

 const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, { phrase: "Phrase 3", categorynumber: 2, optionnumber: 1, }, { phrase: "Phrase 4", categorynumber: 3, optionnumber: 1, }, { phrase: "Phrase 5", categorynumber: 3, optionnumber: 1, }, { phrase: "Phrase 6", categorynumber: 3, optionnumber: 2, }, ];

Me gustaría convertirlo en un Objeto anidado así:

 jsObject = { 1: { 1: ["Phrase 1"], 2: ["Phrase 2"], }, 2: { 1: ["Phrase 3"], }, 3: { 1: ["Phrase 4", "Phrase 5"], 2: ["Phrase 6"], }, };

Esencialmente, el objeto se clasifica según el número de categorynumber y luego el optionnumber . (Tenga en cuenta el formato de "Frase 4" y "Frase 5").

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

0

Reduzca el conjunto de datos accediendo al número de categorynumber como clave principal y al número de optionnumber como clave secundaria. Puede aplicar nuevas opciones a la categoría existente extendiendo ( ... ) la nueva opción y envolviéndola dentro de una matriz.

Si está agregando frases adicionales, también deberá tomar la matriz existente y distribuir el nuevo valor.

 const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, { phrase: "Phrase 3", categorynumber: 2, optionnumber: 1, }, { phrase: "Phrase 4", categorynumber: 3, optionnumber: 1, }, { phrase: "Phrase 5", categorynumber: 3, optionnumber: 1, }, { phrase: "Phrase 6", categorynumber: 3, optionnumber: 2, }, ]; const jsObject = mainData.reduce((acc, { phrase, categorynumber, optionnumber }) => ({ ...acc, [categorynumber]: { ...(acc[categorynumber] ?? {}), [optionnumber]: [...(acc[categorynumber]?.[optionnumber] ?? []), phrase] } }), {}); console.log(jsObject);
 .as-console-wrapper { top: 0; max-height: 100% !important; }
 <!-- jsObject = { 1: { 1: ["Phrase 1"], 2: ["Phrase 2"] }, 2: { 1: ["Phrase 3"] }, 3: { 1: ["Phrase 4", "Phrase 5"], 2: ["Phrase 6"] } } -->

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!