0

(note to mods: this is not a duplicate of 'Fastest way to flatten / un-flatten nested JSON objects' the problem being posed is somewhat different)

I need to transform a string based hierarchal representation of data to a nested javascript object representation.

I figure lodash/collection/reduce is could be useful. But what would be the best way to go about transforming / reducing a format like this;

{
 "a/b/c": 1,
 "a/b/d": 1,
 "e/f/g/h": 1,
 "e/f/g/i/j": 1
}

To something like this?

{ 
  "a": { 
    "b": { 
      "c": 1, 
      "d": 1 
    } 
  },
  "e": {
   "f": {
     "g": {
      "h": 1,
      "i": {
        "j": 1
      }
     }
   }
  }
}
5
  • You don't really need Lodash just to get .reduce() - it's available in modern JavaScript environments on the Array prototype. Commented Dec 2, 2015 at 16:46
  • It you are willing to use ramda (ramdajs.com/0.18.0/docs), mapObjectIndexed and assocPath will help. Commented Dec 2, 2015 at 16:46
  • @pointy actually I got the data structure slightly wrong, I need to operate on an object. Object.reduce is not available in modern JS afaik. Updated example. Commented Dec 2, 2015 at 16:54
  • A good trick that often helps is to use Object.keys() to get the "own" property names of the object as an array, and then use .reduce() with that. Commented Dec 2, 2015 at 17:00
  • @MattRichards I might agree that this is not an exact duplicate, but "I need to transform a string based hierarchal representation of data to a nested javascript object representation." is exactly the problem solved there. Can you be more specific please on how that linked post is not useful for you? What code do you have, what does not work? Are you insisting on using lodash methods? Commented Dec 18, 2015 at 14:03

1 Answer 1

2

split and reduce with native javascript (sorry, not very familiar with lodash)

var testObject = {
 "a/b/c": 1,
 "a/b/d": 1,
 "e/f/g/h": 1,
 "e/f/g/i/j": 1
};

var targetObject = {}

Object.keys(testObject).forEach(function(currentKey) {
  var currentValue = testObject[currentKey];
  currentKey.split('/').reduce(function(generatedObject, generatedKey, currentIndex, array) {
    if (!generatedObject[generatedKey]) {
      generatedObject[generatedKey] = {};
    }
    if (currentIndex == array.length - 1) {
      generatedObject[generatedKey] = currentValue;
    }
    return generatedObject[generatedKey];
  }, targetObject);
});

console.log(targetObject);

Sign up to request clarification or add additional context in comments.

2 Comments

Hi AmmarCSE, thanks for the contribution. I got my example slightly wrong. I've corrected it above.
@MattRichards, check out my updated answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.