Search code examples
appceleratortitanium-mobiletitanium-alloy

Modifying JSON in 2nd window modifies the original JSON in 1st window


I have two windows. In 1st window I have below JSON. I am passing this JSON from 1st window to 2nd window using Alloy.createController("set_schedule", {"data" : data}). In 2nd window I am pushing data to slots, it is modifying the original JOSN of 1st window. I do not want this. It should not modify original data. I have tried storing the args.data to local variable and then manipulating, nothing works.

schedule.js

var data = [{
    "day" : "monday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "tuesday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "wednesday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "thursday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "friday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "saturday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "sunday",
    "slots" : [],
    "duration" : 0
}] 

var win = Alloy.createController("set_schedule", {
    "data" : data
}).getView("setSchedule");
win.open();

set_schedule.js

var scheduleData = args.data; //copy to local variable
scheduleData[0].slots.push({"start": "09:00:00",
    "finish": "17:00:00"});

Now I close set_schedule window and come back to schedule window it is showing

var data = [{
    "day" : "monday",
    "slots" : [{"start": "09:00:00",
    "finish": "17:00:00"}],
    "duration" : 0
}, {
    "day" : "tuesday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "wednesday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "thursday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "friday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "saturday",
    "slots" : [],
    "duration" : 0
}, {
    "day" : "sunday",
    "slots" : [],
    "duration" : 0
}] 

Solution

  • The object you're passing is byref because it's an object. What you should do is clone that object to a new json object:

    var newJsonObj = JSON.parse(JSON.stringify(data));
    

    Note - it might not be the best solution for you (I just don't know what your business logic is).