Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

使用lodash将数据分组

希望高手给出快速分类数据的方法:

数据集合是:

{"mm37_160d_99_00.gif":"SH/DAzRtH4102.gif","mm37_160d_99_01.gif":"SH/DAzRtH42102.gif","mm37_160d_98_01.gif":"SH/DAzDuq6ik357.gif","mm89_160d_99_02.gif":"SH/DAzw583.gif"}

希望能用lodash的函数,将上面的数据集合分的更细如下:

{
    "37":{
        "99":{"mm37_160d_99_00.gif":"SH/DAzRtH4102.gif","mm37_160d_99_01.gif":"SH/DAzRtH42102.gif"},
        "98":{"mm37_160d_98_01.gif":"SH/DAzDuq6ik357.gif"}
    },
    "89":{
        "99":{"mm89_160d_99_02.gif":"SH/DAzw583.gif"}
    }
}

其中,分组依据"mm37_160d_99_00.gif":37是大类,99是小类
如果我格式写的不妥,给你造成了麻烦,十分抱歉。
如果您时间紧张,告诉我哪个函数合适,我自己来琢磨,也可以的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var obj = {"mm37_160d_99_00.gif":"SH/DAzRtH4102.gif","mm37_160d_99_01.gif":"SH/DAzRtH42102.gif","mm37_160d_98_01.gif":"SH/DAzDuq6ik357.gif","mm89_160d_99_02.gif":"SH/DAzw583.gif"};
function formatObj(obj){
    var keys = Object.keys(obj);
    var resultObj  = {};
    for (var i=0;i<keys.length;i++){
        var bigCategory = keys[i].slice(2,4);
        var smallCategory = keys[i].slice(10,12);
        resultObj[bigCategory] = Object.assign({},resultObj[bigCategory]);
        resultObj[bigCategory][smallCategory]= Object.assign({},resultObj[bigCategory][smallCategory]);
        resultObj[bigCategory][smallCategory][keys[i]] = obj[keys[i]];
        
    }
    return resultObj;
}   
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...