1

How does one parse an object with points (.) included in the keys to an multi leveled object?

Example:

{
    "data.firstName": "John",
    "data.lastName": "Doe",
    "data.email": "example@example.org"
}

Expected result:

{
    data: {
        firstName: "John",
        lastName: "Doe",
        email: "example@example.org"
    }
}

PS: You can find collections like this in MongoDB's find query, but I couldn't find how the do it, hence the question.

Jimmy Knoot
  • 2,378
  • 20
  • 29
  • The first expression is not valid JavaScript syntax. – Pointy Nov 03 '14 at 15:42
  • @Pointy how is it not? – Jimmy Knoot Nov 03 '14 at 15:43
  • @JimmyKnoot JavaScript arrays don't use `:` as delimiters between indices. That's object syntac – Sterling Archer Nov 03 '14 at 15:44
  • @JimmyKnoot run it in the console to know how it isn't – Amit Joki Nov 03 '14 at 15:44
  • I see, it's already an object by making it associative, my bad. Edited. – Jimmy Knoot Nov 03 '14 at 15:48
  • Where are you stuck? What have you tried? Have you at least started with a loop? –  Nov 03 '14 at 15:49
  • 1
    This question has already been asked multiple times in multiple forms. Please search. You'll find things like http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference, or http://stackoverflow.com/questions/10934664/convert-string-in-dot-notation-to-get-the-object-reference, and http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key. –  Nov 03 '14 at 16:27

1 Answers1

1

You could do something like:

var data = {
    "data.firstName": "John",
    "data.lastName": "Doe",
    "data.email": "example@example.org"
}

var result = {};  

Object.keys(data).forEach(function (key) {
  var value = data[key]; 
  var keyParent = key.split(".")[0]; 
  var keyChild = key.split(".")[1]; 

  if(!result[keyParent]){
    result[keyParent] = {};
  }

  result[keyParent][keyChild] = value;

});

And the result object would be like the results you are looking for.

frajk
  • 853
  • 6
  • 14
  • 1
    For extra credit, extend your answer to handle multi-part paths. In any case, I doubt if your solution will work if there are keys with different first parts. In that case, your `inner` variable will be polluted with the previous entry. –  Nov 03 '14 at 16:49
  • thanks for pointing that out @torazaburo , was only considering data that op posted. fixed for keys with different first parts. have to think a minute about how to handle multi-part paths – frajk Nov 03 '14 at 18:47
  • You should check if the length of the split is 2 before executing the routine of the child key. – gaelgillard Nov 03 '14 at 19:00