Home > Software engineering >  ES6 - manipulate Object of arrays based on the existence of certain keys
ES6 - manipulate Object of arrays based on the existence of certain keys

Time:11-23

I’m trying to regroup the object values based on keys. The condition to regroup is that

  • the Key has to be ”APTC/IndianEligibility2" or "APTC/CSR”.

  • If these keys exit in the eligibilityGroupingMap object, then append their values to the values of the keys “APTC” and “CSR” if these keys exits

  • else create these keys and push the values.

  • Delete "APTC/IndianEligibility2" & "APTC/CSR" after pushing their values.

    Refer Expected Result

The issue that I’m facing is that I’m getting “Cannot read property 'push' of undefined Javascript”. Tried fixing it by referencing other stack overflow posts. Stuck in it for the last 2 days.

const eligibilityGroupingMap = {
    "CHIP": [
        "CHILD3",
        "CHILD4"
    ],
    "APTC": [
        "SELF1"
    ],
    "APTC/IndianEligibility2": [
        “SPOUSE2”
    ],
    "Ineligible": [
        "CHILD7"
    ],
    "APTC/CSR": [
        "CHILD4"
    ] };

Expected Result:

eligibilityGroupingMap = {
    "CHIP": [
        "CHILD3",
        "CHILD4"
    ],
    "APTC": [
        "SELF1”, “SPOUSE2”, “CHILD4"
    ],
    "CSR": [
        "CHILD4"
    ]
    "Ineligible": [
        "CHILD7"
    ], };

Code Fiddle

const sortedEligibilityGroupingMap = Object.fromEntries(Object.entries(eligibilityGroupingMap).sort());

const sortedMember = Object.keys(sortedEligibilityGroupingMap).reduce((accValue, currValue) => {
        let array = sortedEligibilityGroupingMap[key];
        if(key === 'APTC/CSR' || key === 'APTC/IndianEligibility2' || key === 'APTC/IndianEligibility3') {
            // eslint-disable-next-line no-prototype-builtins
            if('APTC' in sortedEligibilityGroupingMap){
                acc['APTC'].push.apply(sortedEligibilityGroupingMap[key]);
            } else {
                acc.APTC = {};
                acc.APTC = sortedEligibilityGroupingMap[key];
            }
        }
        acc[key] = array.sort();
        delete acc['APTC/CSR'];
          delete acc['APTC/IndianEligibility2'];
                delete acc['APTC/IndianEligibility3'];
                return acc;
}, {});

console.log('sortedMember'. sortedMember);

CodePudding user response:

const eligibilityGroupingMap = {
  CHIP: ["CHILD3", "CHILD4"],
  APTC: ["SELF1"],
  "APTC/IndianEligibility2": ["SPOUSE2"],
  Ineligible: ["CHILD7"],
  "APTC/CSR": ["CHILD4"],
};

const sortedEligibilityGroupingMap = Object.fromEntries(
  Object.entries(eligibilityGroupingMap).sort()
);


let arrayOfKeyMapping = {
  "APTC/CSR": ["APTC", "CSR"],
  "APTC/IndianEligibility2": ["APTC"],
};

let groupedObject = {};

Object.entries(sortedEligibilityGroupingMap).map(([key, value]) => {
  if (arrayOfKeyMapping[key]) {
    let keyList = arrayOfKeyMapping[key];
    keyList.map((mkey) => {
      if (groupedObject.hasOwnProperty(mkey)) {
        groupedObject[mkey].push(...value);
      } else {
        groupedObject[mkey] = [...value];
      }
    });
  } else {
    groupedObject = { ...groupedObject, [key]: value };
  }
});

console.log("final Result", groupedObject);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Probably the problem is so complex and I have some problem to understand it, but why not do something simpler without using loops? Something like:

const copy = {...eligibilityGroupingMap};
copy.APTC = [
  ...(eligibilityGroupingMap.APTC || []),
  ...(eligibilityGroupingMap['APTC/IndianEligibility2'] || []),
  ...(eligibilityGroupingMap['APTC/CSR'] || [])
];
delete copy['APTC/IndianEligibility2'];
delete copy['APTC/CSR'];

If you prefer to keep your code there are several js error:

  1. In the callback you're declaring the params accValue and currValue but you're using those params as acc and key, you should use the same name.
  2. You're checking if APTC is key of sortedEligibilityGroupingMap, but you should check in acc (or accValue, depends which name you've decide to use).
  3. You don't need to delete the keys in the accumulator (this is not an error, just something not needed).
  • Related