Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unflatten a JavaScript object in a daisy-chain/dot notation into an object with nested objects and arrays?

I want to unflatten an object like this...

var obj2 = {
    "firstName": "John",
    "lastName": "Green",
    "car.make": "Honda",
    "car.model": "Civic",
    "car.revisions.0.miles": 10150,
    "car.revisions.0.code": "REV01",
    "car.revisions.0.changes": "",
    "car.revisions.1.miles": 20021,
    "car.revisions.1.code": "REV02",
    "car.revisions.1.changes.0.type": "asthetic",
    "car.revisions.1.changes.0.desc": "Left tire cap",
    "car.revisions.1.changes.1.type": "mechanic",
    "car.revisions.1.changes.1.desc": "Engine pressure regulator",
    "visits.0.date": "2015-01-01",
    "visits.0.dealer": "DEAL-001",
    "visits.1.date": "2015-03-01",
    "visits.1.dealer": "DEAL-002"
};

... into an object with nested objects and arrays like the following:

{
  firstName: 'John',
  lastName: 'Green',
  car: {
    make: 'Honda',
    model: 'Civic',
    revisions: [
      { miles: 10150, code: 'REV01', changes: ''},
      { miles: 20021, code: 'REV02', changes: [
        { type: 'asthetic', desc: 'Left tire cap' },
        { type: 'mechanic', desc: 'Engine pressure regulator' }
      ] }
    ]
  },
  visits: [
    { date: '2015-01-01', dealer: 'DEAL-001' },
    { date: '2015-03-01', dealer: 'DEAL-002' }
  ]
}

Here's my (failed) attempt:

function unflatten(obj) {
    var result = {};

    for (var property in obj) {
        if (property.indexOf('.') > -1) {
            var substrings = property.split('.');

            console.log(substrings[0], substrings[1]);


        } else {
            result[property] = obj[property];
        }
    }

    return result;
};

I quickly started repeating code unnecessarily in order to do the nesting of objects and arrays. This is definitely something that needs recursion. Any ideas?

EDIT: I've also asked the opposite, flatten, in another question.

like image 553
nunoarruda Avatar asked Mar 09 '17 12:03

nunoarruda


People also ask

Can you nest objects in JavaScript?

JavaScript can store data through key-value pairs. The key-value pairs are associated with the JavaScript objects. Objects contain properties that can be stored in nested objects. These nested objects are created within other objects and accessed through dot or bracket notation.

What is flatten object in JavaScript?

We make a function called flatten object which takes input of an object and returns an 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.


1 Answers

You can first use for...in loop to loop object properties, then split each key at . then use reduce to build nested properties.

var obj2 = {"firstName":"John","lastName":"Green","car.make":"Honda","car.model":"Civic","car.revisions.0.miles":10150,"car.revisions.0.code":"REV01","car.revisions.0.changes":"","car.revisions.1.miles":20021,"car.revisions.1.code":"REV02","car.revisions.1.changes.0.type":"asthetic","car.revisions.1.changes.0.desc":"Left tire cap","car.revisions.1.changes.1.type":"mechanic","car.revisions.1.changes.1.desc":"Engine pressure regulator","visits.0.date":"2015-01-01","visits.0.dealer":"DEAL-001","visits.1.date":"2015-03-01","visits.1.dealer":"DEAL-002"}

function unflatten(data) {
  var result = {}
  for (var i in data) {
    var keys = i.split('.')
    keys.reduce(function(r, e, j) {
      return r[e] || (r[e] = isNaN(Number(keys[j + 1])) ? (keys.length - 1 == j ? data[i] : {}) : [])
    }, result)
  }
  return result
}

console.log(unflatten(obj2))
like image 156
Nenad Vracar Avatar answered Nov 07 '22 17:11

Nenad Vracar