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

149
Visualizações
How to recursively map/restructure an object?

I would like an array of objects with all object keys from a nested object. I wrote a recursive function to do this however at the point that the function is recalled it is not going through the object as expected but rather sending back an index infinitely.

let array = [];

const findKeys = (ob) => {
  let id = 0;
  let keys = Object.keys(ob);
  for (let i = 0; i < keys.length; i++) {

    let object = {
      id: id,
      label: keys[i],
    };

    array.push(object);
    id ++;
    findKeys(ob[keys[i]]);
  }
  return array;
};
let newArray = findKeys(data);
console.log(newArray);

example data structure:

const data = {a: {
  b: {
    c: {
      foo: 'bar'
    }
  }
}}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to check to see if you have an object before you do the next recursive call. You also are resetting id so you are going to have the ids repeated (maybe you want that?) and you are using a global for the array so it can not be used more than once.

You are going to want something like:

function getKeys(obj) {

  const array = [];
  let id = 0;

  function loop(obj) {
    Object.entries(obj).forEach(entry => {
      array.push({
        id: ++id,
        label: entry[0],
      });      
      if(entry[1] != null && entry[1].constructor.name === "Object") {
        loop(entry[1]);
      }
    });
  }

  loop(obj);

  return array;
}

const obj1 = { a: 1, b: 'bar' };
console.log(getKeys(obj1));

const obj2 = { a: 1, b: { c: 'bar' } };
console.log(getKeys(obj2));

about 4 years ago · Juan Pablo Isaza Relatório

0

Perhaps you may do like

var data = {a: {
  b: {
    c: {
      foo: 'bar',
      arr: [1,2,3,4]
    }
  }
}};

function getAllKeys(obj){
  var keys = (typeof obj === "object") && (obj !== null) && Object.keys(obj);
  return !!keys ? keys.reduce((r,k) => r.concat(getAllKeys(obj[k])),keys)
                : [];
};

var res = getAllKeys(data);

console.log(JSON.stringify(res));

about 4 years ago · Juan Pablo Isaza Relatório

0

some thing like that

see also Check that value is object literal?

const data = { a: { b: { c: { foo: 'bar' } } }}

const isObject = el => (Object.prototype.toString.call(el) === '[object Object]')

const findKeys = obj => 
  {
  let arr   = []
    , id    = 0
    ;
  getKeys(obj)
  return arr

  function getKeys(o)
    {
    Object.keys(o).forEach(key =>
      { 
      arr.push({ id:id++, label:key })
      if (isObject(o[key]))
        getKeys(o[key])
      })  
    }
  }
  

console.log( findKeys(data) )
.as-console-wrapper {max-height: 100%!important;top:0 }

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