Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda