Skip to content

Instantly share code, notes, and snippets.

@a4amaan
Created April 1, 2020 19:23
Show Gist options
  • Save a4amaan/60b0735b87e367a2b1d518e1cde7a518 to your computer and use it in GitHub Desktop.
Save a4amaan/60b0735b87e367a2b1d518e1cde7a518 to your computer and use it in GitHub Desktop.
Replace key values in nested objects
// find "key_name" and set value "value_to_be_set"
// replacePropertyValue(json_object, "key_name", "value_to_be_set");
replacePropertyValue(obj, search_key, replace_value) {
var replaceValue = replace_value;
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (typeof obj[key] == "object") {
this.replacePropertyValue(
obj[key],
search_key,
replaceValue
);
} else if (key == search_key) {
obj[search_key] = replaceValue;
}
}
return obj;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment