日期相关
// 日期格式化及补0
function formatDate(date) {
const d = new Date(date);
const Y = d.getFullYear() + '-';
const M = (d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1) + '-';
const D = (d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate()) + ' ';
const h = (d.getHours() < 10 ? '0' + (d.getHours()) : d.getHours()) + ':';
const m = (d.getMinutes() < 10 ? '0' + (d.getMinutes()) : d.getMinutes()) + ':';
const s = (d.getSeconds() < 10 ? '0' + (d.getSeconds()) : d.getSeconds());
return Y + M + D + h + m + s;
}
console.log(formatDate('2021/4/6 8:23:45'))
// 得出时间差的格式
function timeAgo(endTime, startTime) {
var stamp = new Date(endTime).getTime() - new Date(startTime).getTime();
var time = (stamp / 1000);
if (time != null && time !== '') {
if (time > 60 && time < 60 * 60) {
time = parseInt(time / 60.0) + '分钟';
} else if (time >= 60 * 60 && time < 60 * 60 * 24) {
time = parseInt(time / 3600.0) + '小时' + parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) + '分钟';
} else if (time >= 60 * 60 * 24) {
time = parseInt(time / 3600.0 / 24) + '天' + parseInt((parseFloat(time / 3600.0 / 24) - parseInt(time / 3600.0 / 24)) * 24) + '小时' + parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) + '分钟';
} else {
time = parseInt(time) + '秒';
}
}
return time;
}
console.log(timeAgo('2021-2-2 1:01:00', '2021-2-1 1:00:00'))
// 时间戳转化成YMD格式
/**
* @param {Number} timestamp 时间戳
* @param {String} formats 输出格式
*/
const dateFormat = (timestamp, formats) => {
// formats格式包括
// 1. Y-m-d
// 2. Y-m-d H:i:s
// 3. Y年m月d日
// 4. Y年m月d日 H时i分
formats = formats || 'Y-m-d';
const zero = function (value) {
if (value < 10) {
return '0' + value;
}
return value;
};
const myDate = timestamp ? new Date(timestamp) : new Date();
const year = myDate.getFullYear();
const month = zero(myDate.getMonth() + 1);
const day = zero(myDate.getDate());
const hour = zero(myDate.getHours());
const minite = zero(myDate.getMinutes());
const second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
})[matches];
});
};
console.log(dateFormat(1618885554444, 'Y年m月d日 H时i分'))
// 根据时间段筛选数据
function filterFun(arr, startT, endT) {
console.log(2, startT, endT);
// 被过滤数据, 开始时间, 结束时间
// filterFun(date, '2021-01-21 09:10', '2021-01-21 20:56')
const searchData = arr.filter(item => {
// 每一项数据时间段
const itemStartStamp = new Date(item.start).getTime();
const itemEndStamp = new Date(item.end).getTime();
// 所搜时间段
const searchStartStamp = new Date(startT).getTime();
const searchEndStamp = new Date(endT).getTime();
// 筛选该时间段数据
if (itemStartStamp >= searchStartStamp && itemEndStamp <= searchEndStamp) {
console.log(item);
return item;
}
});
return searchData;
}
前端搜索
const data = [
{
name: '王小光',
sex: '1',
_id: '1'
},
{
name: '李玉泉',
sex: '2',
_id: '2'
},
{
name: '刘新海',
sex: '1',
_id: '3'
},
{
name: '刘丽妃',
sex: '2',
_id: '4'
},
{
name: '张天涯',
sex: '1',
_id: '5'
},
{
name: '周心苑',
sex: '1',
_id: '6'
},
{
name: '李海燕',
sex: '2',
_id: '7'
}
];
// 通过名字模糊搜索
// 所有待搜索数据, 搜索关键字
function searchName(data, key) {
const keyword = key
const result = data.filter(item => {
if (keyword === '' || item.name.indexOf(keyword) > -1) {
return true;
}
return false;
});
return result;
}
console.log(searchName(data, '刘'))
// 通过姓名和性别搜索
function MultiCriteriaSearch(data, searchName,searchSex) {
const result1 = data.filter(item => {
if (searchSex === '' || item.sex === searchSex) {
return true;
}
return false;
});
const result2 = result1.filter(item => {
if (searchName === '' || item.name.indexOf(searchName) > -1) {
return true;
}
return false;
});
return result2;
}
console.log(MultiCriteriaSearch(data, '王', '1'))
树形结构处理
第一种方法:
/**
* 通过递归调用返回层级树结构
* 1. 克隆原数据 allData
* 2. 在外层对所有数据进行遍历筛选
* 3. 在内层对所有数据进行再次的遍历筛选
* 4. 如果内层没有就将外层筛选条件归到初始状态
* @param {array} allData - 所有的数据
* @return {array} 所有的层级树结构
* @memberof ClassifyService
*/
function getTreeData(allData) {
let cloneData = JSON.parse(JSON.stringify(allData)) // 对源数据深度克隆
return cloneData.filter((father) => {
let branchArr = cloneData.filter((child) => father.id == child.lastId) //返回每一项的子级数组
branchArr.length > 0 ? (father.children = branchArr) : '' //如果存在子级,则给父级添加一个children属性,并赋值
return father.lastId == null //返回第一层
})
}
/**
* @param {array} allData - 所有的树形数据
* @return {array} 所有的扁平化结构
* @memberof ClassifyService
*/
function getFlatData(allData) {
let result = []
const faltFunction = (source) => {
source.forEach((el) => {
result.push(el)
el.children && el.children.length > 0 ? faltFunction(el.children) : ''
})
}
faltFunction(allData)
return result
}
第二种方法:
/**
* constrcut 方法
* 根据提供的 id, pid 和 children 将一个个节点构建成一棵或者多棵树
* @param nodes 节点对象
* @param config 配置对象
*/
export function construct(nodes: object[], config?: Config) {
const id = config && config.id || 'id'
const pid = config && config.pid || 'pid'
const children = config && config.children || 'children'
const idMap = {}
const jsonTree = []
nodes.forEach((v) => { v && (idMap[v[id]] = v) })
nodes.forEach((v) => {
if (v) {
let parent = idMap[v[pid]]
if (parent) {
!parent[children] && (parent[children] = [])
parent[children].push(v)
} else {
jsonTree.push(v)
}
}
})
return jsonTree
}
/**
* destruct 方法
* 根据配置的 id, pid 和 children 把解构化的树型对象拆解为一个个节点
* @param forest 单个或者多个树型对象
* @param config 配置
*/
export function destruct(forest: object[] | object, config?: Config) {
const id = config && config.id || 'id'
const pid = config && config.pid || 'pid'
const children = config && config.children || 'children'
function flatTree(tree: object) {
const queue = [tree]
const result = []
while (queue.length) {
let currentNode = queue.shift()
if (currentNode.hasOwnProperty(id)) {
if (!currentNode.hasOwnProperty(pid)) {
currentNode = { ...currentNode, [pid]: null }
}
if (currentNode[children]) {
currentNode[children].forEach((v) => { v && queue.push({ ...v, [pid]: currentNode[id] }) })
}
result.push(currentNode)
delete currentNode[children]
} else {
throw new Error('you need to specify the [id] of the json tree')
}
}
return result
}
if (Array.isArray(forest)) {
return forest.map((v) => flatTree(v)).reduce((pre, cur) => pre.concat(cur))
} else {
return flatTree(forest)
}
}