Skip to content

Instantly share code, notes, and snippets.

@ndthanh
Forked from tanaikech/submit.md
Created June 16, 2021 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndthanh/22d687b6d7f30421c023dd1490dc104f to your computer and use it in GitHub Desktop.
Save ndthanh/22d687b6d7f30421c023dd1490dc104f 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