0


js常用的数据转换方法(日期,树tree)

本文主题:数据转换方法

创作日期:2020.08.28

个人主页:KinHKin的博客_CSDN博客-vue,性能优化,前端开发规范领域博主

在前端开发中,数据类型转换十分常见,本文记录的目的是方便后续的查阅和使用。

1.1第一种方法:

new Date()的格式转换成指定分隔符的格式

  1. let date = new Date();
  2. // 转成 YYYY-MM-DD 格式
  3. // 只需要传入分隔符 缺点不够扩展
  4. function formatDateToString(date, foramt = "-") {
  5. return (
  6. date.getFullYear() +
  7. foramt +
  8. (date.getMonth() + 1) +
  9. foramt +
  10. date.getDate()
  11. );
  12. }
  13. console.log(formatDateToString(date, "."));
  14. console.log(
  15. date.getFullYear(),
  16. date.getMonth() + 1,
  17. date.getDate(),
  18. date.getHours(),
  19. date.getMinutes(),
  20. date.getSeconds()
  21. );
  22. 输出:2022 8 28 11 17 19
  23. 2022.8.28

1.2 第二种方法

在原生Date对象的原型链上封装,好处实用性强,范围广

  1. / Date的扩展,将 Date 转化为指定格式的String
  2. // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
  3. // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  4. // 例子:
  5. // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  6. // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  7. Date.prototype.Format = function (fmt) {
  8. var o = {
  9. "M+": this.getMonth() + 1, //月份
  10. "d+": this.getDate(), //日
  11. "H+": this.getHours(), //小时
  12. "m+": this.getMinutes(), //分
  13. "s+": this.getSeconds(), //秒
  14. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  15. S: this.getMilliseconds(), //毫秒
  16. };
  17. if (/(y+)/.test(fmt))
  18. fmt = fmt.replace(
  19. RegExp.$1,
  20. (this.getFullYear() + "").substr(4 - RegExp.$1.length)
  21. );
  22. for (var k in o)
  23. if (new RegExp("(" + k + ")").test(fmt))
  24. fmt = fmt.replace(
  25. RegExp.$1,
  26. RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  27. );
  28. return fmt;
  29. };
  30. // 调用:
  31. var time1 = new Date().Format("yyyy-MM-dd");
  32. var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
  33. console.log(time1, time2);
  34. 输出:2022-08-28 2022-08-28 11:21:57

2.string类型转Date

  1. let str = '2020-09-20 20:20:10'
  2. console.log(new Date(str))
  3. 输出:2020-09-20T12:20:10.000Z

3.数组转为tree

一个一维数组要想能转化为树,必须至少包含2个字段,id和parentId。id是每个节点的唯一性标识;parentId是父id的意思,用于建立节点之间的关联。

  1. // toTree 函数用于把一维数组转换为tree
  2. function toTree(data, config) {
  3. const { id = "id", parentId: pId = "parentId" } = config || {};
  4. const ids = data.map((item) => item[id]);
  5. const result = [],
  6. waitRes = [];
  7. data.forEach((item) => {
  8. if (ids.includes(item[pId])) {
  9. waitRes.push(item);
  10. } else {
  11. result.push(item);
  12. }
  13. });
  14. const flatData = [...result];
  15. while (waitRes.length) {
  16. const flatIds = flatData.map((f) => f[id]);
  17. const node = waitRes.find((w) => flatIds.includes(w[pId]));
  18. const parNode = flatData.find((f) => f[id] === node[pId]);
  19. waitRes.splice(waitRes.indexOf(node), 1);
  20. if (parNode.children) {
  21. parNode.children.push(node);
  22. } else {
  23. parNode.children = [node];
  24. }
  25. flatData.push(node);
  26. }
  27. return result;
  28. }
  29. const json = [
  30. { id: 1, parentId: -1, name: "menu-1" },
  31. { id: 3, parentId: 2, name: "menu-1 item-1" },
  32. { id: 2, parentId: 1, name: "menu-1-1" },
  33. { id: 4, parentId: -1, name: "menu-2" },
  34. { id: 5, parentId: 4, name: "menu-2 item-1" },
  35. ];
  36. console.log(JSON.stringify(toTree(json), null, 2));
  37. 输出:[
  38. {
  39. "id": 1,
  40. "parentId": -1,
  41. "name": "menu-1",
  42. "children": [
  43. {
  44. "id": 2,
  45. "parentId": 1,
  46. "name": "menu-1-1",
  47. "children": [
  48. {
  49. "id": 3,
  50. "parentId": 2,
  51. "name": "menu-1 item-1"
  52. }
  53. ]
  54. }
  55. ]
  56. },
  57. {
  58. "id": 4,
  59. "parentId": -1,
  60. "name": "menu-2",
  61. "children": [
  62. {
  63. "id": 5,
  64. "parentId": 4,
  65. "name": "menu-2 item-1"
  66. }
  67. ]
  68. }
  69. ]

4.tree转数组类型

4.1第一种方法

  1. /**
  2. * 树转数组扁平化结构
  3. * 深度优先遍历 堆栈 后进先出
  4. */
  5. function toArray(node) {
  6. let stack = node,
  7. data = [];
  8. while (stack.length != 0) {
  9. let pop = stack.pop();
  10. data.push({
  11. id: pop.id,
  12. name: pop.name,
  13. parentId: pop.parentId,
  14. });
  15. let children = pop.children;
  16. if (children) {
  17. for (let i = children.length - 1; i >= 0; i--) {
  18. stack.push(children[i]);
  19. }
  20. }
  21. }
  22. return data;
  23. }
  24. let resceshi = [
  25. {
  26. id: 1,
  27. parentId: -1,
  28. name: "menu-1",
  29. children: [
  30. {
  31. id: 2,
  32. parentId: 1,
  33. name: "menu-1-1",
  34. children: [
  35. {
  36. id: 3,
  37. parentId: 2,
  38. name: "menu-1 item-1",
  39. },
  40. ],
  41. },
  42. ],
  43. },
  44. {
  45. id: 4,
  46. parentId: -1,
  47. name: "menu-2",
  48. children: [
  49. {
  50. id: 5,
  51. parentId: 4,
  52. name: "menu-2 item-1",
  53. },
  54. ],
  55. },
  56. ];
  57. console.log(toArray(resceshi), "tree转数组");
  58. 输出:[
  59. { id: 4, name: 'menu-2', parentId: -1 },
  60. { id: 5, name: 'menu-2 item-1', parentId: 4 },
  61. { id: 1, name: 'menu-1', parentId: -1 },
  62. { id: 2, name: 'menu-1-1', parentId: 1 },
  63. { id: 3, name: 'menu-1 item-1', parentId: 2 }
  64. ] tree转数组

4.2第二种方法

  1. /**
  2. * 树转数组扁平化结构
  3. * 深度优先遍历 递归
  4. */
  5. function deepTraversal(data) {
  6. const result = [];
  7. data.forEach(item => {
  8. const loop = data => {
  9. result.push({
  10. id: data.id,
  11. name: data.name,
  12. parentId: data.parentId
  13. });
  14. let child = data.children
  15. if(child){
  16. for(let i = 0; i < child.length; i++){
  17. loop(child[i])
  18. }
  19. }
  20. }
  21. loop(item);
  22. })
  23. return result;
  24. }

4.3第三种方法

  1. /**
  2. * 广度优先
  3. * 队列 先进先出
  4. */
  5. function wideTraversal(node){
  6. let stack = node,
  7. data = [];
  8. while(stack.length != 0){
  9. let shift = stack.shift();
  10. data.push({
  11. id: shift.id,
  12. name: shift.name,
  13. parentId: shift.parentId
  14. })
  15. let children = shift.children
  16. if(children){
  17. for(let i = 0; i < children.length; i++){
  18. stack.push(children[i])
  19. }
  20. }
  21. }
  22. return data
  23. }

本文转载自: https://blog.csdn.net/weixin_42974827/article/details/126566952
版权归原作者 KinHKin 所有, 如有侵权,请联系我们删除。

“js常用的数据转换方法(日期,树tree)”的评论:

还没有评论