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
      }
     }
   }
  }
}
Matt Richards
  • 1,477
  • 2
  • 14
  • 21
  • You don't really need Lodash just to get `.reduce()` - it's available in modern JavaScript environments on the Array prototype. – Pointy Dec 02 '15 at 16:46
  • It you are willing to use ramda (http://ramdajs.com/0.18.0/docs), mapObjectIndexed and assocPath will help. – nha Dec 02 '15 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. – Matt Richards Dec 02 '15 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. – Pointy Dec 02 '15 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? – Bergi Dec 18 '15 at 14:03

1 Answers1

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);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53