I am generating a form that is constructed from JSON. I've successfully created the form, but I am now trying to figure out how to update the specific item in JSON from the user input. I've seen this question asked using node and underscore, etc but I would like to accomplish this with vanilla JS or jQuery.
I am trying to avoid modifying the JSON other than the values as it will need to be sent back in the same format, and I am able to find an item by its key or value, however the problem I have is that there are multiple k/v pairs in each object that I am using. Here is an example object:
var list = {
"parent": {
"item" : {
"id" : "a1b295",
"name" : "sample name",
"value" : "this is a sample value"
}
}
My form elements come out as <input type="text" name="a1b295" value="this is a sample value" />
What I am trying to do is on submit, iterate through the form elements and update each object in the JSON. I am struggling to figure out how to look up the item by its id and then update the value key value pair for that object.
To be clear the data can have any number of nested children, and I need to go after the ones with specific IDs which I am already turning into form inputs.
Thank you.
This is what I have attempted but it returns a "can't access id of undefined" error.
function traverseData(data, obj)
{
for (var k in data)
{
if (typeof data[k] == "object" && data[k] !== null) {
traverseData(obj[k], obj);
} else if (!data.hasOwnProperty(k)) {
continue;
} else if (k = obj) {
console.log(obj);
}
}
}
traverseData(data, $(this).attr('id'));