Skip to content

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 }

In JavaScript, you can flatten an object using a recursive function that iterates over the object’s properties and flattens them into a single-level object.

function flattenObject(obj) {
  let result = {};
  for (let key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      let flatObject = flattenObject(obj[key]);
      for (let flatKey in flatObject) {
        result[key + '.' + flatKey] = flatObject[flatKey];
      }
    } else {
      result[key] = obj[key];
    }
  }
  return result;
}

let myObject = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA',
    zip: '12345'
  }
};

let flattenedObject = flattenObject(myObject);
console.log(flattenedObject);

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading