Categories
JavaScript Answers

How to Unflatten a JSON Object with JavaScript?

Spread the love

To unflatten a flattened JavaScript object, we can split each property path and add the nested properties into the unflatten object.

To do this, we write:

const unflatten = (data) => {
  if (Object(data) !== data || Array.isArray(data))
    return data;
  const regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/
  const props = Object.keys(data);
  let result, p;
  while (p = props.shift()) {
    const m = regex.exec(p)
    let target;
    if (m.index) {
      const rest = p.slice(0, m.index);
      if (!(rest in data)) {
        data[rest] = m[2] ? [] : {};
        props.push(rest);
      }
      target = data[rest];
    } else {
      if (!result) {
        result = (m[2] ? [] : {});
      }
      target = result
    }
    target[m[2] || m[1]] = data[p];
  }
  return result;
};

console.log(unflatten({
  'a[0].b[0]': "c",
  'a[0].b[1]': "d"
}))

We create the unflatten function to do the unflattering of a flattened object.

It takes the data parameter which can be anything.

In the function,m we check if data isn’t an object or is an array.

If either is true, then we return data as is.

Otherwise, we have the regex to parse the property path.

props has the keys from data .

We then loop through the keys and call regex.exec to get the property path parts and assign it to m .

Next, we get the index of the extracted property parts.

We then check if the property path path is in data .

If it’s not, then we add it to data .

And then we call props.push with rest to props .

Then we assign data[rest] to target to update targer .

Otherwise, we assign result to target .

If there are no property parts left, we add the target ‘s property to data.

And then we return result .

Now when we run the unflatten function, we should see an object with the a property with an array value.

And in it, we have the b property with an array value with 'c' and 'd' inside.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.