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

211
Visualizações
ES6 - manipulate Object of arrays based on the existence of certain keys

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);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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).
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