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

232
Views
¿Cuál es la mejor manera de lograr el siguiente resultado?

tengo los siguientes datos:

 const data = [ { id: 1, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'blue', }, { type: 'size', value: 'small', }, ], }, }, { id: 2, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'blue', }, ], }, }, { id: 3, metadata: { attributes: [ { type: 'background', value: 'red', }, { type: 'background', value: 'green', }, { type: 'size', value: 'small', }, ], }, }, ];

Para cada objeto en la matriz de atributos, tengo que crear un nuevo objeto basado en la propiedad de tipo. La propiedad de tipo será una clave en este nuevo objeto y el valor será otra propiedad anidada dentro. El valor de la propiedad anidada será una matriz que contiene todos los identificadores correspondientes. Entonces, tengo que lograr algo como esto como resultado final:

 const desiredResult = { background: { red: [1, 2, 3], //these are ids blue: [1, 2], green: [3], }, size: { small: [1, 3], }, };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede probar for each o for ... of en javascript. código limpio para principiantes como a continuación:

 function process (data) { let result = {}; for (let datum of data) { for (let attribute of datum.metadata.attributes) { result[attribute.type] = result[attribute.type] || {}; result[attribute.type][attribute.value] = result[attribute.type][attribute.value] || []; result[attribute.type][attribute.value].push(datum.id); } } return result; } // const desiredResult = process(data);
about 4 years ago · Juan Pablo Isaza Report

0

Otro enfoque muy parecido a los otros aquí, pero usando datos inmutables, incluso para el acumulador:

 const extract = (xs) => xs .reduce ((a, {id, metadata: {attributes = []} = {}}) => attributes .reduce ((a, {type: t, value: v}) => ({...a, [t]: {... (a [t] || {}), [v]: [...((a [t] || {}) [v] || []), id]}}), a), {}) const data = [{id: 1, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}, {type: "size", value: "small"}]}}, {id: 2, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}]}}, {id: 3, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "green"}, {type: "size", value: "small"}]}}] console .log (extract (data))
 .as-console-wrapper {max-height: 100% !important; top: 0}

Esto funciona para muchos tamaños de datos, pero puede generar un problema de rendimiento si los datos son realmente grandes. Si lo hace, es posible que deba elegir un acumulador mutable en su lugar. Pero no me preocuparía a menos que esta función muestre ser un cuello de botella en su aplicación.

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!