Home > OS >  how to aggregate and do validation on array of object JavaScript?
how to aggregate and do validation on array of object JavaScript?

Time:09-25

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"
          }

CodePudding user response:

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;
}, {}));

CodePudding user response:

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; }

  • Related