fork download
  1. const string = `fizz = 3
  2. buzz.one = item1
  3. buzz.one = item2
  4. buzz.one.two = 123
  5. fizzbuzz.root.a.b.c = 13`;
  6.  
  7. let result = {};
  8.  
  9. const splited = string.split("\n");
  10.  
  11. function insertIntoTree(tree, keyParts, value) {
  12. let current = tree;
  13.  
  14. for (let i = 0; i < keyParts.length - 1; i++) {
  15. const part = keyParts[i];
  16.  
  17. if (!current[part]) {
  18. current[part] = {};
  19. }
  20.  
  21. current = current[part];
  22. }
  23.  
  24. const lastKey = keyParts[keyParts.length - 1];
  25.  
  26. if (current.hasOwnProperty(lastKey)) {
  27. if (!Array.isArray(current[lastKey])) {
  28. current[lastKey] = [current[lastKey]];
  29. }
  30. current[lastKey].push(value);
  31. } else {
  32. current[lastKey] = value;
  33. }
  34. }
  35.  
  36. splited.forEach((line) => {
  37. const [key, value] = line.split("=").map((s) => s.trim());
  38.  
  39. const parsedValue = isNaN(value) ? value : Number(value);
  40.  
  41. const keyParts = key.split(".");
  42.  
  43. insertIntoTree(result, keyParts, parsedValue);
  44. });
  45.  
  46. console.log(JSON.stringify(result, null, 2));
  47.  
Success #stdin #stdout 0.03s 17456KB
stdin
Standard input is empty
stdout
{
  "fizz": 3,
  "buzz": {
    "one": [
      "item1",
      "item2"
    ]
  },
  "fizzbuzz": {
    "root": {
      "a": {
        "b": {
          "c": 13
        }
      }
    }
  }
}