JS 偶爾學一點 Lodash -> keyBy
_.keyBy(陣列/物件變數, 迭代方法);
常使用的狀況是,你想讓物件/陣列裡的某個值變成key以方便之後使用
var obj_vars = {
"3": {sn: 1, title: "t1"},
"2": {sn: 2, title: "t2"},
"1": {sn: 3, title: "t3"},
};
_.keyBy(obj_vars, "sn");
/**
{
"1": {
"sn": 1,
"title": "t1"
},
"2": {
"sn": 2,
"title": "t2"
},
"3": {
"sn": 3,
"title": "t3"
}
}
*/
var arr_vars = [
{sn: 3, title: "t3"},
{sn: 2, title: "t2"},
{sn: 1, title: "t1"},
];
_.keyBy(arr_vars , "sn");
/**
{
"1": {
"sn": 1,
"title": "t1"
},
"2": {
"sn": 2,
"title": "t2"
},
"3": {
"sn": 3,
"title": "t3"
}
}
*/
進階學習(或許你需要更進接的判斷)
var arr_vars = [
{sn: 3, title: "t3"},
{sn: 2, title: "t2"},
{sn: 1, title: "t1"},
];
_.keyBy(arr_vars , (obj) => {
return obj.sn + 7;
});
/**
{
"8": {
"sn": 1,
"title": "t1"
},
"9": {
"sn": 2,
"title": "t2"
},
"10": {
"sn": 3,
"title": "t3"
}
}
*/
留言
張貼留言