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

172
Visualizações
How to flatten nested object to an array of objects

I need to flatten nested object to an array of objects. So far this is what i came up with. But it is not working properly. Currently I'm checking the current element is object or not, if it is an object I'm calling same function recursively.

As the output i need this.

[
 {title: 'Foo', value: 111},
 {title: 'Bar', value: 222},
 ...
]
var data = {
  1: {
    title: "Foo",
    value: 111,
    children: {
      2: {
        title: "Bar",
        value: 222,
      },
    },
  },
  3: {
    title: "Baz",
    value: 333,
    children: {
      4: {
        title: "Qux",
        value: 444,
        children: {
          5: {
            title: "Quux",
            value: 555,
          },
        },
      },
    },
  },
};

const finalArrayOfObjects = [];

  const flattenObject = (obj) => {
    const flattened = {};

    Object.keys(obj).forEach((key) => {
      if (typeof obj[key] === "object" && obj[key] !== null) {
        flattenObject(obj[key]);
      } else {
        flattened[key] = obj[key];
      }

      finalArrayOfObjects.push(flattened);
      console.log(flattened);
    });
  };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Here's one way, using a recursive generator function.

var data = {
  1: {
    title: "Foo",
    value: 111,
    children: {
      2: {
        title: "Bar",
        value: 222,
      },
    },
  },
  3: {
    title: "Baz",
    value: 333,
    children: {
      4: {
        title: "Qux",
        value: 444,
        children: {
          5: {
            title: "Quux",
            value: 555,
          },
        },
      },
    },
  },
};

function *forAllChildren(obj) {
  for (let key in obj) {
    let { children, ...objWithoutChildren} = obj[key];
    yield objWithoutChildren;
    yield *forAllChildren(obj[key].children);
  }
}

const result = [...forAllChildren(data)]
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Hope this work for you

var finalArrayOfObjects = [];

var flattenObject = (obj) => {

    for(var key in obj) {
        // { title , value, children}
        var data = obj[key]
        if (data.children) {
            // data.children = { key : {title , value, children} }
            flattenObject(data.children)
        }
        finalArrayOfObjects.push({
            title : data.title,
            value : data.value,
        })
    }
}
flattenObject(data)
console.log(finalArrayOfObjects)
about 4 years ago · Juan Pablo Isaza Relatório

0

Time to once again prove the power of Functional Programming & Recursion

var data = {
        1: {
          title: "Foo",
          value: 111,
          children: {
            2: {
              title: "Bar",
              value: 222,
            },
          },
        },
        3: {
          title: "Baz",
          value: 333,
          children: {
            4: {
              title: "Qux",
              value: 444,
              children: {
                5: {
                  title: "Quux",
                  value: 555,
                },
              },
            },
          },
        },
      };

  const dictAsArray = Object.values(data);
  const flat = [];

  function drill(array) {
    array.map(obj => {
       recursiveCall(obj);
      });
   }

  function recursiveCall(obj) {
    if (obj.children) {
      const children = JSON.parse(JSON.stringify(Object.values(obj.children)));
      delete obj.children; 
      drill(children);
    }

    flat.push(obj);
  }

  dictAsArray.map(dict => recursiveCall(dict));
  console.log(flat);

In this approach the children objects are removed from each object. If you would like them to remain though, you can simply remove delete obj.children.

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