PDA

View Full Version : Resolved JSON - How to add/remove data


CharlieCA
04-01-2010, 03:28 PM
Sorry if this question is basic but I haven't seem to run across anything that talks about how to add and remove data from a JSON object.


var work = { "days" : [
{ "date" : "3/1/2010",
"totalhours" : "6",
"jobs" : [
{ "hours" : "5",
"job_name" : "Clean"},
{ "hours" : "2",
"job_name" : "Cook"}
],
},
{ "date" : "3/2/2010",
"totalhours" : "2",
"jobs" : [
{ "hours" : "1",
"job_name" : "Wash"},
{ "hours" : "1",
"job_num" : "Scrub"}
],
}],
};


For example, how would I add a job to work.days[1].jobs or delete work.days[0].jobs[0]?

TinyScript
04-01-2010, 04:20 PM
<script>

var work = { "days" : [
{ "date" : "3/1/2010",
"totalhours" : "6",
"jobs" : [
{ "hours" : "5",
"job_name" : "Clean"},
{ "hours" : "2",
"job_name" : "Cook"}
]
},
{ "date" : "3/2/2010",
"totalhours" : "2",
"jobs" : [
{ "hours" : "1",
"job_name" : "Wash"},
{ "hours" : "1",
"job_num" : "Scrub"}
]
}]
};

window.onload=function(){

work.days[0].jobs.push({"hours" : "1","job_name" : "CodingForum"})//add a job

alert(work.days[0].jobs[2].job_name)

work.days[0].jobs.splice(2,1)//remove item from jobs array at 3rd position in array

if(work.days[0].jobs[2]){alert(work.days[0].jobs[2].job_name)}else{alert("error. no array member at that position")}

}

</script>


I did the alerts to show that the object gets inserted into the array and then gets removed
I removed the extra commas you had in your arrays