Created
April 1, 2024 19:46
-
-
Save Mahabali/08ae4d77825b68c3cbcd67ae20c33fb7 to your computer and use it in GitHub Desktop.
Run through each key in json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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