Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
What is the best way to achieve the following result?

I have the following data:

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',
        },
      ],
    },
  },
];

For each object in the attributes array I have to create a new object based on the type property. The type property will be a key in this new object and the value will be another property nested inside. The value of the nested property will be an array that contains all the corresponding ids. So, I have to achieve something like this as a final result:

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 Respuestas
Responde la pregunta

0

You can try for each or for ... of in javascript. clean code for beginner like below:

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 Denunciar

0

Another approach much like the others here, but using immutable data, even for the accumulator:

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}

This works for many sizes of data, but it can run into a performance problem if the data is really large. If you do, then you might have to choose a mutable accumulator instead. But I wouldn't worry about it unless this function shows itself to be a bottleneck in your application.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda