Skip to content

Instantly share code, notes, and snippets.

@Mahabali
Created April 1, 2024 19:46
Show Gist options
  • Save Mahabali/08ae4d77825b68c3cbcd67ae20c33fb7 to your computer and use it in GitHub Desktop.
Save Mahabali/08ae4d77825b68c3cbcd67ae20c33fb7 to your computer and use it in GitHub Desktop.
Run through each key in json
const appendRandomStringToKeys = (obj, randomString) => {
const isObject = (val) => typeof val === 'object' && !Array.isArray(val) && val !== null;
Object.keys(obj).forEach((key) => {
if (key !== '_typename' && key !== 'Instrumentquery') {
const newKey = key + randomString;
obj[newKey] = obj[key];
delete obj[key];
if (isObject(obj[newKey])) {
appendRandomStringToKeys(obj[newKey], randomString);
} else if (Array.isArray(obj[newKey])) {
obj[newKey].forEach((item) => {
if (isObject(item)) {
appendRandomStringToKeys(item, randomString);
}
});
}
} else if (isObject(obj[key]) || Array.isArray(obj[key])) {
appendRandomStringToKeys(obj[key], randomString);
}
});
};
// Example usage
const randomString = "__randomString"; // Define your random string here
appendRandomStringToKeys(data, randomString);
console.log(JSON.stringify(data, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment