如何将嵌套数组存储在tanpermonkey, 再通过元素排序显示到控制台?

我想把网站打开的次数和时间存储在tampermonkey,我直接存储发现不能排序,因为数组没有名称,如何将嵌套数组存放在tampermonkey,再通过次数排序,显示到控制台?

在这个脚本上添加了count函数https://greasyfork.org/zh-CN/scripts/404859

function count(a) {
        let d = new Date();

        if(GM_getValue(a)){
            GM_setValue(a, {
                'times': GM_getValue(a).times + 1,
                'date': d
            });
        }else{
            GM_setValue(a, {
                'times': 1,
                'date': d
            });
        }
    }

油猴存储数据

{
    "Github": {
        "times": 1,
        "date": "2021/01/31 4:5:1"
    },
    "Google": {
        "times": 2,
        "date": "2021/01/31 12:11:33"
    },
    "Greasyfork": {
        "times": 1,
        "date": "2021/01/31 4:1:21"
    },
}

然后我发现对数组排序的方法,需要存放在有名字的嵌套数组里面,这样写了只能存放当前打开的图标网站的次数和时间,打开其他的图标网站会被覆盖

function count(a) {
        let d = new Date();
        
        if(GM_getValue('Times')){
            GM_getValue('Times').forEach(function(value) {
                if(value.name === a){
                    var m = [{
                        'name': a,
                        'times': value.times + 1,
                        'date': timetext
                    }]

                    GM_setValue('Times', m);
                }else{
                    m = [{
                        'name': a,
                        'times': 1,
                        'date': timetext
                    }]
                    GM_setValue('Times', m);
                }
            });
        } else {
            var m = [{
                'name':a,
                'times': 1,
                'date': timetext
            }]
            GM_setValue('Times', m);
        }
    }

数组排序的方法

 let allValue = GM_listValues();
    allValue.splice(allValue.indexOf('search'),1);

    allValue.sort(compare( "times"));

    function compare( propertyName) {
        return function( object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if (value1 < value2) {
                return 1;
            } else if (value1 > value2) {
                return - 1;
            } else {
                return 0;
            }
        }
    }

如果油猴存放的数据是嵌套数组,就可以调用排序的函数了,达到的效果是这样

{
    "search": "",
    "Times": [
        {
            "name": "Github",
            "times": 6,
            "date": "2021/01/31 18:43:15"
        },
        {
            "name": "Google",
            "times": 4,
            "date": "2021/01/31 18:43:15"
        },
        {
            "name": "Greasyfork",
            "times": 1,
            "date": "2021/01/31 18:43:15"
        }
    ]
}
阅读 2.2k
1 个回答

读取存储在tampermonkey数据,存在新建的数组里面,再排序

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题