Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created August 20, 2017 23:41
Show Gist options
  • Save tanaikech/4c659fbb7cf8df0bc2c063dafa10e36c to your computer and use it in GitHub Desktop.
Save tanaikech/4c659fbb7cf8df0bc2c063dafa10e36c to your computer and use it in GitHub Desktop.
Changing Values by Checking Duplicated Values of JSON for Javascript

Changing Values by Checking Duplicated Values of JSON for Javascript

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"
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment