从克隆的JavaScript对象中删除密钥会更改原始对象

时间:2015-07-22 18:56:02

标签: javascript jquery json

我有一个非常大的JSON事件源,我通过AJAX将其引入JavaScript。一旦我将对象放在内存中,我希望能够使用它而不是每次都进行新的AJAX调用。

我有一个允许过滤JSON事件的表单。在初始过滤时,我的函数复制原始对象(以保留它),然后当它们与过滤条件不匹配时从新对象中删除键。

第一次运行这组函数时,这非常有效。但是,再次运行时,似乎原始对象被更改,然后触发JavaScript错误。

当我console.debug原始对象时,我可以看到它第一次运行时,它是一个预期的对象。在进一步的运行中,它看起来像是以某种方式转换为对象数组。

我已经简化了代码以显示问题:

json = [{"title": "Title 1","time": 1},{"title": "Title 2","time": 1},{"title": "Title 3","time": 2},{"title": "Title 4","time": 2},{"title": "Title 5","time": 3},{"title": "Title 6","time": 3},{"title": "Title 7","time": 4},{"title": "Title 8","time": 4},{"title": "Title 9","time": 5},{"title": "Title 10","time": 5}];
jQuery('a').on('click touch tap', function(){
    propEvents(json);
    return false;
});
//End prep code for example


function propEvents(json){
    var loadFromMemory = 0;

    if ( loadFromMemory == 0 ){
        globalEventObject = json;
        loadFromMemory = 1;
    }


    console.log('Initial Global Object:');
    console.debug(globalEventObject);

    //Filter the JSON
    filteredEventsObject = eventSearch(globalEventObject);

    //The global object was never filtered, but keys are being removed from it too... I need to store it in memory to start filters from scratch each time.
    console.log('Global Object After Filter:');
    console.debug(globalEventObject);
}


function eventSearch(events){
    var tempObject = events; //May be unnecessary, but for example purposes.

    jQuery(tempObject).each(function(i){
        if ( tempObject[i].time != 3 ){
            console.log('no match: removing this event');
            delete tempObject[i]; //Remove this key from the tempObject
            return;
        }
    });

    tempObject = tempObject.filter(function(){return true;}); //Start the keys from 0 again.
    console.log('Length of filtered object:');
    console.debug(tempObject.length);
    return tempObject;
}

Here it is in CodePen您可以在其中查看控制台日志。这让我把车轮旋转了好几天,而我却无法绕过它。任何线索都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

var tempObject = events;实际上并未克隆该对象。相反,它会var tempObject指向events,随后,您对tempObject的任何副作用也会发生在events上。

有很多方法可以克隆对象,有关详细信息,请参阅此SO问题:What is the most efficient way to deep clone an object in JavaScript?

由于您提及您尝试操作JSON Feed,我建议

var clone = JSON.parse(JSON.stringify(events))

并操纵clone

答案 1 :(得分:1)

JavaScript将对象作为引用副本传递。请关注此帖以获取更多详细信息。

StackOverflow