Flatten object JavaScript | single-depth Object

  • by

Just concat all keys and values to get Flatten object in JavaScript. If the values are already at a single depth then it returns the result unaltered

Example flatten object JavaScript

Simple flat object example code in JavaScript

<!DOCTYPE html>
<html>
<body>

  <script>
    const obj = { 1: 'Apple', 2: 'Cherry', 3: 'Mango' };  

    result = Object.keys(obj).reduce(function (r, k) {
      return r.concat(k, obj[k]);
    }, []);

    console.log(result);

  </script>

</body>
</html> 

Output:

Flatten object JavaScript

Here is another working example without a key.

const flatten=(obj)=>Object.values(obj).flat()

const x={x:[1,2,3],y:[4,5,6,7]}

console.log(flatten(x))

Output: [ 1, 2, 3, 4, 5, 6, 7 ]

Objects into a single-depth Object

Loop through the object and check the type of the current property:

  • If it is of type Object and it is not an Array, recursively call the function again.
  • Otherwise, store the value in the result.
<script>
    let ob = {
      Company: "EyeHunts",
      Address: "Bangalore",
      contact: +91-999999999,
      code: {
        HTML: 200,
        CSS: 500,
        JavaScript: 100
      }
    };

    const flattenObj = (ob) => {

      let result = {};

      for (const i in ob) {

        if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
          const temp = flattenObj(ob[i]);
          for (const j in temp) {

            result[i + '.' + j] = temp[j];
          }
        }

        else {
          result[i] = ob[i];
        }
      }
      return result;
    };

    console.log(flattenObj(ob));
 </script>

Output:

Object { Company: “EyeHunts”, Address: “Bangalore”, contact: -999999908, “code.HTML”: 200, “code.CSS”: 500, “code.JavaScript”: 100 }

Do comment if you have any doubts or suggestions on this JS object code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.