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

250
Views
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 answers
Answer question

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 Report

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 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!