Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!