Last active
April 1, 2020 19:22
-
-
Save a4amaan/7d32321020233e76c66fc5f71d969618 to your computer and use it in GitHub Desktop.
Search Object in Nested Json and Update Property Value
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
// 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