My issue is presented in a much simpler manner.
Here is the json (you can view it here if you wish)
{"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303"},{"name":"OFF","id":"304"}]}]},{"id":"1408694995","obj":[{"id":"3","action":[{"name":"ON","id":"305"},{"name":"OFF","id":"306"}]},{"id":"4","action":[{"name":"ON","id":"307"},{"name":"OFF","id":"308"}]}]}]}
If given an ID (in this case, let's say ID = 3), I need to save the item with that ID. Then, I must store in a new object (newobj) the object with that ID, but changing the array ACTION to an OBJ with only the action ON.
Illustration
<script>
var tt = '{"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303"},{"name":"OFF","id":"304"}]}]},{"id":"1408694995","obj":[{"id":"3","action":[{"name":"ON","id":"305"},{"name":"OFF","id":"306"}]},{"id":"4","action":[{"name":"ON","id":"307"},{"name":"OFF","id":"308"}]}]}]}';
var myjson = JSON.parse(tt);
var search = 3;
console.log(myjson.resource[1].obj[0]);
for(var i = 0 ; i < myjson.resource.length; i++){
for(j = 0 ; j < myjson.resource[i].obj.length; j++){
if(parseInt(myjson.resource[i].obj[j].id) == search){
var newobj = myjson.resource[i].obj[j];
var obj_action = newobj.action;
for(var k = 0 ; k < obj_action.length ; k++){
if(obj_action[k].name == "ON"){
newobj.action = obj_action[k];
}
}
}
}
}
console.log(myjson.resource[1].obj[0]);
</script>
I am able to successfully save the desired object in the newobj variable. However, why does the original JSON get altered?
UPDATE
It appears that the issue lies in how I'm storing the obj in the newobj variable. It seems like I'm saving a reference to the object in the JSON rather than the object itself. How can I save it in the newobj variable without creating a reference?