JSON object update

Hi there!

I have a pretty complex structure in the db for one of my cell. It's a json object with this configuration:
sites: [
{'_id': '1',
'name': 'My site 1'
},
{'_id': '2',
'name': 'My site 2'
}
]


I have a request with 'site_id' and 'form_name' inputs. What i am trying to do is to find the site based on input 'site_id', that matches the '_id' value and create a new key:value pair so the object looks like this:
sites: [
{'_id': '1',
'name': 'My site 1', 'forms':[{'name':'my_form'}]
},
{'_id': '2',
'name': 'My site 2'
}
]

So far my logic is:

1. find first element in array based on 'site_id' in input, it should match the '_id' value.

2. create a variable 'current_site_forms' that would return the forms array if it exists or null if there is no such key

3. create a variable 'updated_site_forms' and either set the new key:value pair with forms to it or update the existing 'forms' array with new object {'name':'form_name'}

4. now i need to update the sites array with the updated element that has 'forms' array without destroying the original sites array. I am stuck on this step, can anyone put me in the right direction?

Thank you!

2 replies