JS_js修改无限级数组对象键名

「爱情、让人受尽委屈。」 2022-09-11 13:28 208阅读 0赞

需求:替换数组对象中ids为id,name为label,当children为空数组的时候,删除children子节点

方法一

  1. let list = [{
  2. ids: 1,
  3. name: '蔬菜',
  4. children: []
  5. },
  6. {
  7. ids: 2,
  8. name: '水果',
  9. children: [{
  10. ids: 22,
  11. name: '香蕉',
  12. children: []
  13. }]
  14. }
  15. ]
  16. var key = 'childrens'
  17. function parseJson(arr) {
  18. arr = arr.slice()
  19. function toParse(arr) {
  20. arr.forEach(function(item) {
  21. item.label = item.name
  22. delete item.name
  23. if (item.children.length > 0 && Array.isArray(item.children)) {
  24. item[key] = item.children
  25. toParse(item[key])
  26. }
  27. delete item.children
  28. })
  29. return arr
  30. }
  31. return toParse(arr)
  32. }
  33. console.log(parseJson(list))

方法二

  1. let list = [{
  2. ids: 1,
  3. name: '蔬菜',
  4. children: []
  5. },
  6. {
  7. ids: 2,
  8. name: '水果',
  9. children: [{
  10. ids: 22,
  11. name: '香蕉',
  12. children: []
  13. }]
  14. }
  15. ]
  16. let stlist = JSON.stringify(list);
  17. stlist = stlist.replace(/\"ids"/g, '"id"');
  18. stlist = stlist.replace(/\"name"/g, '"label"');
  19. stlist = stlist.replace(new RegExp(/(,"children":\[\])/g), '');
  20. console.log(JSON.parse(stlist));

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,208人围观)

还没有评论,来说两句吧...

相关阅读