Skip to content

Instantly share code, notes, and snippets.

@a4amaan
Last active April 1, 2020 19:22
Show Gist options
  • Save a4amaan/7d32321020233e76c66fc5f71d969618 to your computer and use it in GitHub Desktop.
Save a4amaan/7d32321020233e76c66fc5f71d969618 to your computer and use it in GitHub Desktop.
Search Object in Nested Json and Update Property Value
// https://stackoverflow.com/questions/17988939/find-and-update-in-nested-json-object/17991517
// update set key_to_update = value_to_be_set where key = key_to_be_mached
// this.searchObjects(json_object,"key", "key_to_be_mached", "key_to_update", "value_to_be_set")
searchObjects(obj, search_key, search_val, replace_key, replace_value) {
var replaceValue = replace_value;
var objects = [];
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (typeof obj[key] == "object") {
objects = objects.concat(
this.searchObjects(
obj[key],
search_key,
search_val,
replace_key,
replaceValue
)
);
} else if (key == search_key && obj[search_key] == search_val) {
obj[replace_key] = replaceValue;
}
}
return obj;
}
this.searchObjects(
object_to_be_searched,
"id",
element.field_id,
"selected_value",
element.field_value
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment