Javascript 如何在缓存中放置和读取复杂对象?

Javascript 如何在缓存中放置和读取复杂对象?,javascript,jquery,Javascript,Jquery,我有以下代码添加了一个javascript复杂对象(树),您可以将其视为一个数组数组,其中值本身就是对象 我想像这样放入缓存: localStorage.Terms = tree; 但在控制台中读取时,它显示为object object function GetTermsDataFromTaxonomy(){ var start = new Date().getTime(); //Current Context var context = SP.ClientContex

我有以下代码添加了一个javascript复杂对象(树),您可以将其视为一个数组数组,其中值本身就是对象

我想像这样放入缓存:

localStorage.Terms = tree;
但在控制台中读取时,它显示为
object object

function GetTermsDataFromTaxonomy(){
    var start = new Date().getTime();
    //Current Context
    var context = SP.ClientContext.get_current();           
    //Current Taxonomy Session
    var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);           
    //Term Stores
    var termStores = taxSession.get_termStores();           
    //Name of the Term Store from which to get the Terms.
    var termStore = termStores.getByName("Taxonomy_kl5tZjInn7STsFTzIE7n3Q==");          
    //GUID of Term Set from which to get the Terms.
    var termSet = termStore.getTermSet("31da4bc1-6429-499a-9d5e-be5e18b13c87");         
    var terms = termSet.getAllTerms();          
    context.load(terms);

    context.executeQueryAsync(function(){   
            var termEnumerator = terms.getEnumerator(), tree = {
                term: terms,
                children: []
            };
            var termList = "Terms: \n";                 
            while(termEnumerator.moveNext()){                       
                var currentTerm = termEnumerator.get_current(); 
                var currentTermPath = currentTerm.get_pathOfTerm().split(';');
                var children = tree.children;

                 // Loop through each part of the path
                for (var i = 0; i < currentTermPath.length; i++) {
                    var foundNode = false;        
                    for (var j = 0; j < children.length; j++) {
                        if (children[j].name === currentTermPath[i]) {
                            foundNode = true;
                            break;
                        }
                    }

                    // Select the node, otherwise create a new one
                    var term = foundNode ? children[j] : { name: currentTermPath[i], children: [] };

                    // If we're a child element, add the term properties
                    if (i === currentTermPath.length - 1) {
                        term.term = currentTerm;
                        term.title = currentTerm.get_name();
                        term.guid = currentTerm.get_id().toString();
                    }

                    // If the node did exist, let's look there next iteration
                    if (foundNode) {
                        children = term.children;
                    }
                    // If the segment of path does not exist, create it
                    else {
                        children.push(term);

                        // Reset the children pointer to add there next iteration
                        if (i !== currentTermPath.length - 1) {
                            children = term.children;
                        }
                    }
                }               
            }
            localStorage.Terms = tree;
            var end = new Date().getTime();
            var time = end - start;
            console.log('Execution time: ' + time);             
        },
            function(sender,args){          
              console.log(args.get_message());              
        });
}


function GetAllTermsRecursive(){
    if(typeof(Storage) !== "undefined") 
    {
        var lastRefreshDateFromTermStore = localStorage.LastRefreshDateFromTermStore;

        //get data when the code is executed
        var currentDate = new Date();
        var day = currentDate.getDate();
        var month = currentDate.getMonth() + 1;
        var year = currentDate.getFullYear();
        var today = new Date(year, month, day, 0,0,0,0);

        if(lastRefreshDateFromTermStore < today){
            localStorage.removeItem('Terms');
            localStorage.removeItem('LastRefreshDateFromTermStore');            
        }

        //Check if data has been cached.
        if(typeof(localStorage.Terms)  !== "undefined")
        {   
            var start = new Date().getTime();
            var terms=localStorage.Terms;
            var end = new Date().getTime();
            var time = end - start;
            console.log('Execution time with cache: ' + time);
        }
        else
        {
            //get date for when the data is cached
            var currentDate = new Date();
            var day = currentDate.getDate();
            var month = currentDate.getMonth() + 1;
            var year = currentDate.getFullYear();
            var cachedDate = new Date(year, month, day, 0,0,0,0);

            localStorage.LastRefreshDateFromTermStore = cachedDate;
            GetTermsDataFromTaxonomy();         
        }           
    }
    else {
            alert("Cache not sopported in old browsers, please upgrade");
    }   
}
函数GetTermsDataFromTaxonomy(){
var start=new Date().getTime();
//当前上下文
var context=SP.ClientContext.get_current();
//当前分类会议
var taxSession=SP.Taxonomy.TaxonomySession.getTaxonomySession(上下文);
//术语库
var termStores=taxSession.get_termStores();
//从中获取术语的术语库的名称。
var termStore=termStores.getByName(“分类法”\u kl5tZjInn7STsFTzIE7n3Q==”;
//要从中获取术语的术语集的GUID。
var termSet=termStore.getTermSet(“31da4bc1-6429-499a-9d5e-be5e18b13c87”);
var terms=termSet.getAllTerms();
上下文。加载(术语);
context.executeQueryAsync(函数(){
var termnumerator=terms.getEnumerator(),树={
术语:术语,
儿童:[]
};
var termList=“术语:\n”;
while(termEnumerator.moveNext()){
var currentTerm=termEnumerator.get_current();
var currentTermPath=currentTerm.get_pathOfTerm().split(“;”);
var children=tree.children;
//循环通过路径的每个部分
对于(var i=0;i
您只能在
localStorage
中存储字符串值。无论何时尝试保存
对象
类型,都会调用其
toString
方法,这当然会导致
[Object Object]

通常使用
JSON.stringify
保存数据(对象的字符串表示)

JSON.parse
当您检索回数据时:

var terms = JSON.parse(localStorage.Terms);

这个对象是循环的,似乎不起作用,我们得到了一个错误:将循环结构转换为JSON,你知道吗?是的,你不能字符串化循环引用。您必须找到一种存储更简单结构的方法。不完整的树。实际上,您可以在树对象上定义
toJSON
方法,该方法将返回用于JSON序列化的必要对象。
var terms = JSON.parse(localStorage.Terms);