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

248
Vistas
how to aggregate and do validation on array of object JavaScript?

i have a array which contains many object and i want to aggregate both array into one object on some validation like if same key have value in both object then the output object's key vale should be blank if one key have value only in single one then value should present in output object and example:

let userValues = [
                {
                    "userId": "810",
                    "values": {
                        "21866": "Russia",
                        "21867": "Dog",
                        "21868": ""
                    },
                },
                {
                    "userId": "811",
                    "values": {
                        "21866": "UAE",
                        "21867": "",
                        "21868": "cheddar cheese"
                    },
                }
            ]
let aggricagtedValue= {
              "21866": "",
              "21867": "Dog",
              "21868": "cheddar cheese"
          }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This way can help you:

const data = [
  {
    "userId": "810",
    "values": {
      "21866": "Russia",
      "21867": "Dog",
      "21868": ""
    },
  },
  {
    "userId": "811",
    "values": {
      "21866": "UAE",
      "21867": "",
      "21868": "cheddar cheese"
    },
  }
];

console.log(Object.values(data.reduce((acc, {values}) => {
  Object.keys(values).forEach((key) => {
    if (!acc[key]) acc[key] = {key, values: []};
    if (values[key].length > 0) acc[key].values.push(values[key]);
  });
  return acc;
}, {})).reduce((acc, {key, values}) => {
  const _values = values.filter(item => item.length > 0).filter((value, index, self) => self.indexOf(value) === index);
  acc[key] = _values.length === 1 ? _values[0] : '';
  return acc;
}, {}));

about 4 years ago · Juan Pablo Isaza Denunciar

0

function collectGroupedValues(result, { values }, idx, arr) {
  // main aggregation task ...
  result = Object
    .entries(values)
    .reduce((obj, [key, value]) => {
      // ... which straightforwardly pushes items into an array.
      if (key in obj) {
        obj[key].push(value);
      } else {
        obj[key] = [value];
      }
      return obj;
    }, result);

  // finalizing aggregation task ...
  if (idx >= arr.length - 1) {
    result = Object.fromEntries(Object
      .entries(result)
      .map(([key, valueList]) => {
        // ... which sanitizes each array ...
        valueList = valueList
          .filter(value =>
            // (filter empty strings from array)
            value.trim() !== ''
          );
        // ... an on top of the sanitized
        // result does create the final entry.
        return [
          key,
          (valueList.length === 1) ? valueList[0] : '',
        ];
      })
    );
  }
  return result
}
let userValues = [{
  "userId": "810",
  "values": {
    "21866": "Russia",
    "21867": "Dog",
    "21868": "",
  },
}, {
  "userId": "811",
  "values": {
    "21866": "UAE",
    "21867": "",
    "21868": "cheddar cheese",
  },
}];

console.log({ userValues });
console.log(userValues.reduce(collectGroupedValues, {}));

userValues.push({
  "userId": "812",
  "values": {
    "21866": "France",
    "21867": "Goat",
    "21868": "fromage",
  }
});

console.log({ userValues });
console.log(userValues.reduce(collectGroupedValues, {}));
.as-console-wrapper { min-height: 100%!important; top: 0; }

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