-1

I have a json object I would like to modify. This is data:

var data1 = {
  "a@1.0.3": {
    "b@2.3.0": {
      "c@2.0.0": {
        "d@0.4.0": {
          "e@1.1.1": {}
        },
        "f@0.5.3": {}
      },
      "j@2.15.2": {
      "x@1.2.3": {}
      }
    },
    "i@1.5.8": {}
  }
};

basically for every key, a the left of '@' I want to add char + sum of every number on the right and on the right replace all '.' with '-'. For example, if key is 'abcd@1.12.4', my new key will be 'abcd17@1-12-4'. for this example I want this as result:

var data2 = {
      "a4@1-0-3": {
        "b5@2-3-0": {
          "c2@2-0-0": {
            "d4@0-4-0": {
              "e3@1-1-1": {}
            },
            "f8@0-5-3": {}
          },
          "j19@2-15-2": {
          "x6@1-2-3": {}
          }
        },
        "i14@1-5-8": {}
      }
    };

can you please help ?

dmx
  • 1,862
  • 3
  • 26
  • 48

1 Answers1

2

Here is a working fiddle. The code is:

var data1 = {
  "a@1.0.3": {
    "b@2.3.0": {
      "c@2.0.0": {
        "d@0.4.0": {
          "e@1.1.1": {}
        },
        "f@0.5.3": {}
      },
      "j@2.15.2": {
      "x@1.2.3": {}
      }
    },
    "i@1.5.8": {}
  }
};

console.log(JSON.stringify(fixData(data1)));

function fixData(data) {
    var result = {};
    for (var key in data) {
    if (data.hasOwnProperty(key)) {
        if (key.indexOf("@") == -1)
        continue; // Ignore keys without @'s

        var parts = key.split("@");
      var left = parts[0];
      var right = parts[1];

      // Replace .'s with -'s
      while (right.indexOf(".") > -1) {
        right = right.replace(".", "-");
      }

      // Add up values
      var num = 0;
      var splits = right.split("-");
      for (var i = 0; i < splits.length; i++) {
        var chars = splits[i];
        if (!isNaN(chars)) {
            num += parseInt(chars);
        }
      }
      left += num;

      // Replace key
      var existing = data[key];
      result[left+"@"+right] = fixData(existing);
    }
  }

  return result;
}

This gives:

{  
   "a4@1-0-3":{  
      "b5@2-3-0":{  
         "c2@2-0-0":{  
            "d4@0-4-0":{  
               "e3@1-1-1":{  

               }
            },
            "f8@0-5-3":{  

            }
         },
         "j19@2-15-2":{  
            "x6@1-2-3":{  

            }
         }
      },
      "i14@1-5-8":{  

      }
   }
}
JosephGarrone
  • 4,081
  • 3
  • 38
  • 61