Subject of this article: Data Transformation Methods
Creation date: 2020.08.28
Personal homepage: KinHKin's blog_CSDN blog - vue, performance optimization, blogger in the field of front-end development specification
In front-end development, data type conversion is very common. The purpose of this document is to facilitate subsequent reference and use.
Table of contents
1. date to string type
1.1 The first method:
The format of new Date() is converted to the format of the specified separator
let date = new Date();
// 转成 YYYY-MM-DD 格式
// 只需要传入分隔符 缺点不够扩展
function formatDateToString(date, foramt = "-") {
return (
date.getFullYear() +
foramt +
(date.getMonth() + 1) +
foramt +
date.getDate()
);
}
console.log(formatDateToString(date, "."));
console.log(
date.getFullYear(),
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
);
输出:2022 8 28 11 17 19
2022.8.28
1.2 The second method
Encapsulated on the prototype chain of the native Date object, the benefits are strong practicability and wide range
/ 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
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;
};
// 调用:
var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
console.log(time1, time2);
输出:2022-08-28 2022-08-28 11:21:57
2. String type to Date
let str = '2020-09-20 20:20:10'
console.log(new Date(str))
输出:2020-09-20T12:20:10.000Z
3. Convert array to tree
If a one-dimensional array can be converted into a tree, it must contain at least two fields, id and parentId. id is the unique identifier of each node; parentId is the meaning of the parent id, which is used to establish the association between nodes.
// toTree 函数用于把一维数组转换为tree
function toTree(data, config) {
const { id = "id", parentId: pId = "parentId" } = config || {};
const ids = data.map((item) => item[id]);
const result = [],
waitRes = [];
data.forEach((item) => {
if (ids.includes(item[pId])) {
waitRes.push(item);
} else {
result.push(item);
}
});
const flatData = [...result];
while (waitRes.length) {
const flatIds = flatData.map((f) => f[id]);
const node = waitRes.find((w) => flatIds.includes(w[pId]));
const parNode = flatData.find((f) => f[id] === node[pId]);
waitRes.splice(waitRes.indexOf(node), 1);
if (parNode.children) {
parNode.children.push(node);
} else {
parNode.children = [node];
}
flatData.push(node);
}
return result;
}
const json = [
{ id: 1, parentId: -1, name: "menu-1" },
{ id: 3, parentId: 2, name: "menu-1 item-1" },
{ id: 2, parentId: 1, name: "menu-1-1" },
{ id: 4, parentId: -1, name: "menu-2" },
{ id: 5, parentId: 4, name: "menu-2 item-1" },
];
console.log(JSON.stringify(toTree(json), null, 2));
输出:[
{
"id": 1,
"parentId": -1,
"name": "menu-1",
"children": [
{
"id": 2,
"parentId": 1,
"name": "menu-1-1",
"children": [
{
"id": 3,
"parentId": 2,
"name": "menu-1 item-1"
}
]
}
]
},
{
"id": 4,
"parentId": -1,
"name": "menu-2",
"children": [
{
"id": 5,
"parentId": 4,
"name": "menu-2 item-1"
}
]
}
]
4. Tree to array type
4.1 The first method
/**
* 树转数组扁平化结构
* 深度优先遍历 堆栈 后进先出
*/
function toArray(node) {
let stack = node,
data = [];
while (stack.length != 0) {
let pop = stack.pop();
data.push({
id: pop.id,
name: pop.name,
parentId: pop.parentId,
});
let children = pop.children;
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i]);
}
}
}
return data;
}
let resceshi = [
{
id: 1,
parentId: -1,
name: "menu-1",
children: [
{
id: 2,
parentId: 1,
name: "menu-1-1",
children: [
{
id: 3,
parentId: 2,
name: "menu-1 item-1",
},
],
},
],
},
{
id: 4,
parentId: -1,
name: "menu-2",
children: [
{
id: 5,
parentId: 4,
name: "menu-2 item-1",
},
],
},
];
console.log(toArray(resceshi), "tree转数组");
输出:[
{ id: 4, name: 'menu-2', parentId: -1 },
{ id: 5, name: 'menu-2 item-1', parentId: 4 },
{ id: 1, name: 'menu-1', parentId: -1 },
{ id: 2, name: 'menu-1-1', parentId: 1 },
{ id: 3, name: 'menu-1 item-1', parentId: 2 }
] tree转数组
4.2 The second method
/**
* 树转数组扁平化结构
* 深度优先遍历 递归
*/
function deepTraversal(data) {
const result = [];
data.forEach(item => {
const loop = data => {
result.push({
id: data.id,
name: data.name,
parentId: data.parentId
});
let child = data.children
if(child){
for(let i = 0; i < child.length; i++){
loop(child[i])
}
}
}
loop(item);
})
return result;
}
4.3 The third method
/**
* 广度优先
* 队列 先进先出
*/
function wideTraversal(node){
let stack = node,
data = [];
while(stack.length != 0){
let shift = stack.shift();
data.push({
id: shift.id,
name: shift.name,
parentId: shift.parentId
})
let children = shift.children
if(children){
for(let i = 0; i < children.length; i++){
stack.push(children[i])
}
}
}
return data
}