1.js简单的id pid数据生成树状结构,其中id和pid为实际的数据字段
function toTree(data,id,pid) {
// 删除 所有 children,以防止多次调用
data.forEach(function (item) {
delete item.children;
});
// 将数据存储为 以 id 为 KEY 的 map 索引数据列
var map = {};
data.forEach(function (item) {
map[item[id]] = item;
});
var val = [];
data.forEach(function (item) {
// 以当前遍历项的pid,去map对象中找到索引的id
var parent = map[item[pid]];
// 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
val.push(item);
}
});
return val;
}
2.获取地址栏(url)参数并且转为对象
var GetQueryJson2 = function () {
let url = location.href; // 获取当前浏览器的URL
let param = {}; // 存储最终JSON结果对象
url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
param[v] = decodeURIComponent(k);//解析字符为中文
return k + '=' + v;
});
return param;
}
console.log(getQueryObject ("http://www.test.net?id=123&a=1&bb=b"));
//{id: "123", a: "1", bb: "b"}
3.模糊搜索树形结构数据(返回搜索后的树)
deepFind(treeData, value, child, label) {
//treeData:需要遍历的树形数据 value:搜索的关键字'
//child:child字段; label:显示的文字
let treeArr = [];
treeData.forEach((item) => {
if (item[label].indexOf(value) > -1) {
treeArr.push(item)
} else {
if (item[child] && item[child].length > 0) {
let tempData = state.deepFind(item[child], value, child, label)
if (tempData && tempData.length > 0) {
let tempObj = {
...item,
[child]: tempData
};
treeArr.push(tempObj);
}
}
}
})
return treeArr;
}
4.原生日期格式化
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}