Open In App

How to unflatten an object with the paths for keys in JavaScript ?

Last Updated : 12 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to unflatten an object which has a certain number of key-value pairs(s) within it with the paths for the keys in JavaScript.

Problem Statement: You are given an object with several key-value pair(s). Some keys have various keys names present after a dot, you basically need to unflatten that object. You could achieve a path by which it would be easier to distinguish the keys and their values separately.

Approach: We first need to declare an object which would initially have different key-value pairs. There are several key names which we need to segregate and show under the same main object consisting of that particular key with its value.

For example, “car.seat.0.seater” represents a nested object in the car object which is further an array consisting of “seater” key at its first index corresponding with its value.

Let us first try to understand that how we could create an object which would have several key-value pairs(s) in JavaScript.

Example 1: The following code snippet will help us in creating an object.

Javascript




<script> 
 let object = {
    "firstName": "Hello",
    "lastName": "World",
    "car.name": "Duster",
    "car.price": 9.9,
    "car.mileage": 16.42,
    "car.seat.0.seater": 5,
    "car.seat.1.seatLength": 4360,
  };
  console.log(object);
 </script>


Output:

{
  'firstName': 'Hello',
  'lastName': 'World',
  'car.name': 'Duster',
  'car.price': 9.9,
  'car.mileage': 16.42,
  'car.seat.0.seater': 5,
  'car.seat.1.seatLength': 4360
}

After creating the object with several key-value pairs, now we will analyze the approaches through which we could achieve the unflattened object. Following are some approaches to achieve the above-mentioned goal.

Approach 1: 

  • In this approach, we will use for-in loop which will iterate through our object and thereafter we will store our keys in a variable and whenever we will encounter a dot we will use the split() method to have all the key names.
  • We will use reduce() method which will help us to check whether the next key is a number or not after converting a string to a number.
  • Then we will use JSON.stringify() method which will help us to print our object more effectively by converting all the object’s values into corresponding strings values.

Javascript




<script>
  let object = {
    firstName: "Hello",
    lastName: "World",
    "car.name": "Duster",
    "car.price": 9.9,
    "car.mileage": 16.42,
    "car.seat.0.seater": 5,
    "car.seat.0.seatLength": 4360,
  };
  
  let unflattenObject = (data) => {
    let result = {};
    for (let i in data) {
      let keys = i.split(".");
      keys.reduce((acc, value, index) => {
        return (
          acc[value] ||
          (acc[value] = isNaN(Number(keys[index + 1]))
            ? keys.length - 1 === index
              ? data[i]
              : {}
            : [])
        );
      }, result);
    }
    return result;
  };
  console.log(JSON.stringify(
    unflattenObject(object), null, 4));
</script>


Output:

{
    "firstName": "Hello",
    "lastName": "World",
    "car": {
        "name": "Duster",
        "price": 9.9,
        "mileage": 16.42,
        "seat": [
            {
                "seater": 5,
                "seatLength": 4360
            }
        ]
    }
}

Approach 2:

  • In this approach, we will first iterate over our object and also use the split() method whenever there is a dot after any key name.
  • While looping over the substrings obtained after splitting, we will first check if the next substring is a number or not.
  • If it is not a number then it will represent one of the key names of an object otherwise it’s an index of an array, so accordingly we will add our values in either an empty object or an empty array.

Javascript




<script> 
 let object = {
    firstName: "Hello",
    lastName: "World",
    "car.name": "Duster",
    "car.price": 9.9,
    "car.mileage": 16.42,
    "car.seat.0.seater": 5,
    "car.seat.0.seatLength": 4360,
  };
  let unflatten = (obj) => {
    let result = {},
      temp,
      substrings,
      property,
      i;
    for (property in obj) {
      substrings = property.split(".");
      temp = result;
      for (i = 0; i < substrings.length - 1; i++) {
        if (!(substrings[i] in temp)) {
          if (isFinite(substrings[i + 1])) {
            temp[substrings[i]] = [];
          } else {
            temp[substrings[i]] = {};
          }
        }
        temp = temp[substrings[i]];
      }
      temp[substrings[substrings.length - 1]] = obj[property];
    }
   return result;
  };
 console.log(JSON.stringify(unflatten(object), null, 4));
</script>


Output:

{
    "firstName": "Hello",
    "lastName": "World",
    "car": {
        "name": "Duster",
        "price": 9.9,
        "mileage": 16.42,
        "seat": [
            {
                "seater": 5,
                "seatLength": 4360
            }
        ]
    }
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads