I have a json looking like so:
{
"itemsList": [{
"id": 187994,
"contentName": "Content",
"contentItems": [{
"name": "nested 1",
"description": "<p>nested 1</p>\n"
}, {
"name": "nested 2 ",
"description": "<p>nested 2</p>\n"
}]
}]
}
And I am importing this data to an update form and trying to update the value for nested 1 when I submit the form but it keeps only the updated value, somehow it keeps only the updated value the other values get wiped out.
The function below updates the contentItems object but it keeps only the updated content:
$("#editResourceItemForm").submit(function (e) {
e.preventDefault();
$.getJSON(appDirLocation + "public/_data/resource_data.json", function (jsonData) {
console.log(jsonData.itemsList.contentItem);
//var contentItems = jsonData.itemsList.contentItems;
var resourceId = $("#editResourceItemForm input#resourceId").val(); // resource id
var updatedContentName = $("#appData").data("content-name");
var updatedContentItem = {
name: $("#editResourceItemForm input#contentItemName").val(),
description: CKEDITOR.instances.contentItemDescription.getData()
};
resourceId = Number(resourceId); // input filed is collected as string needs to make number
_.each(jsonData.itemsList, function (item) {
if (item.id === resourceId) {
item.contentName = updatedContentName;
item.contentItems = updatedContentItem ;
// queue here new items to update
}
}); // used underscore.js seems better for handling json data
var newJsonOutput = JSON.stringify(jsonData); //stringify new data
var jsonFile = new BCAPI.Models.FileSystem.File(appDirLocation + "public/_data/resource_data.json");
jsonFile.upload(newJsonOutput).done(function () {
$("#contentItemsList").html(""); //clear old data to load new
console.log("RESOURCE DATA UPDATED");
$('#editResourceItem').foundation('close'); //close reveal after created and saved file
renderResourceItems(resourceId);
}).fail(function (jqXHR) {
console.log("RESOURCES JSON FAILED UPDATE: " + jqXHR.responseText);
}); // END OF JSON CREATING
console.log(newJsonOutput);
}).done(function (dataprocessed) {
console.log(dataprocessed);
}).fail(function (jqXHR) {
console.log("Request failed." + "Error code: " + jqXHR.status + "Error text: " + jqXHR.statusText + "Response text: " + jqXHR.responseText);
});
});
Please let me know what I can do to pass the updated values to the existing contentItems without wiping out the rest of the data in the object.
This is the fiddle I used to create the data: https://jsfiddle.net/RicardoAlves/zb5dprvv
Thanks