Open In App

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

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.




<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: 




<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:




<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
            }
        ]
    }
}

Article Tags :