Changing Values by Checking Duplicated Values of JSON for Javascript

Gists

This sample script is for changing values by checking duplicated values of JSON for Javascript.

Please see the following script. There is an array with a JSON data with 3 keys and 3 values. It is found that the values for each element duplicate. These duplicated values are changing by adding numbers.

I use this for managing filenames. This script also can be used for Google Apps Script. If this was useful for you, I’m glad.

Script :

var data = [
    { key1: "value_a1", key2: "value_a2", key3: "value_a3" },
    { key1: "value_b1", key2: "value_a2", key3: "value_b3" },
    { key1: "value_c1", key2: "value_c2", key3: "value_b3" },
    { key1: "value_a1", key2: "value_d2", key3: "value_d3" },
    { key1: "value_e1", key2: "value_a2", key3: "value_a3" },
];
var temp = {};
for (i in data) {
    for (key in data[i]) {
        if (temp[data[i][key]]) {
            temp[data[i][key]] += 1;
            data[i][key] = data[i][key] + "_" + temp[data[i][key]].toString();
        } else {
            temp[data[i][key]] = 1;
        }
    }
}
console.log(data);

Result :

[
  {
    "key1": "value_a1",
    "key2": "value_a2",
    "key3": "value_a3"
  },
  {
    "key1": "value_b1",
    "key2": "value_a2_2",
    "key3": "value_b3"
  },
  {
    "key1": "value_c1",
    "key2": "value_c2",
    "key3": "value_b3_2"
  },
  {
    "key1": "value_a1_2",
    "key2": "value_d2",
    "key3": "value_d3"
  },
  {
    "key1": "value_e1",
    "key2": "value_a2_3",
    "key3": "value_a3_2"
  }
]

 Share!