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

200
Visualizações
How to get the output { a: 123, bcde: 4, f: 5, gh: 67, }; in javascript
const input = {
   a: [1, 2, 3],
   b: {
    c: {
     d: {
       e: 4,
     },
    }, 
  }, 
 f: 5,
 g: {
   h: [6, 7],
 },  
};

const outPut = {
 a: 123,
 bcde: 4,
 f: 5,
 gh: 67,
}; 

const getAllKeysOfObject = (obj, key) => {
   let tempKey = key;
   let nextKey = ''
   if (obj instanceof Object && Object.values(obj).length > 0) {
      nextKey = Object.values(obj)[0]     
      tempKey += nextKey;
      getAllKeysOfObject(obj[nextKey], nextKey)
   } else {
     return {key: tempKey, value: obj[nextKey]}
   } 
 }

const getObject = (input) => {
   let tempObj = {}
   Object.keys(input).forEach(key => {
   let value = input[key]  //[1,2]
   console.log(value)
   if (Array.isArray(value)) {
      let tempStr = ''
      for(let i =0;i<value.length;i++) {
         tempStr += value[i]
      }
      tempObj[key] = tempStr;
   } else if (input[key] instanceof Object && Object.values(input[key]).length > 0) {
     let newObj = getAllKeysOfObject(input[key], key)
     tempObj[newObj.key] = newobj.value 
   } else {
     tempObj[key] = input[key]
   }
  })
  return tempObj
}

console.log(getObject(input))

How to get the output { a: 123, bcde: 4, f: 5, gh: 67, }; in javascript

The above code not working as expected for a key working fine but the nested object getting failed. Getting the error Uncaught TypeError: Cannot read properties of undefined (reading '')"

JSFiddle link https://jsfiddle.net/ankitg1602/5v2gp64r/49/

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can create recursive function with reduce method and if the current value is not an object add to accumulator param and also keep track of previous keys and pass them down.

const input = {
  a: [1, 2, 3],
  b: {
    c: {
      d: {
        e: 4,
      },
    },
  },
  f: 5,
  g: {
    h: [6, 7],
  },
};

function getOutput(data, pk = '') {
  return Object.entries(data).reduce((r, [k, v]) => {
    const key = pk + k

    if (typeof v === 'object' && !Array.isArray(v)) {
      Object.assign(r, getOutput(v, key))
    } else {
      r[key] = Array.isArray(v) ? Number(v.join('')) : v
    }

    return r;
  }, {})
}

console.log(getOutput(input))

about 4 years ago · Juan Pablo Isaza Relatório

0

You could get the entries with recursion.

This approach does not need to hand over the last keys.

const
    getEntries = object => Object
        .entries(object)
        .flatMap(([k, v]) => v && typeof v === 'object' && !Array.isArray(v)
            ? getEntries(v).map(([l, r]) => [k + l, r])
            : [[k, [].concat(v).join('')]]
        ),
    input = { a: [1, 2, 3], b: { c: { d: { e: 4 } } }, f: 5, g: { h: [6, 7] } },
    result = Object.fromEntries(getEntries(input));

console.log(result);

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