js实现树形结构的节点排序编码

 js实现树形结构的节点排序编码_第1张图片

js实现树形结构的节点排序编码_第2张图片

function encodeTree(array,config) {
  let encodedArray = [];
  let counter = 1;
  const order=config.order
  const children=config.children
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    const encodedItem = { ...item, [order]: counter++ };

    if (Array.isArray(item[children]) && item[children].length > 0) {
      encodedItem[children] = encodeTree(item[children],config);
    }
    encodedArray.push(encodedItem);
  }
  return encodedArray;
}

// 排序前
const inputArray = [
  { name: '节点1', childNode: [] },
  { name: '节点2', childNode: [
    { name: '子节点2-1', childNode: [] },
    { name: '子节点2-2', childNode: [] }
  ]},
  { name: '节点3', childNode: [
    { name: '子节点3-1', childNode: [] }
  ]}
];
console.log(inputArray,'原数组');
const encodedArray = encodeTree(inputArray,{order:'codeNumber',children:'childNode'});
console.log(encodedArray,'排序数组');

//排序后
const encodedArray=[
    {
        "name": "节点1",
        "childNode": [],
        "codeNumber": 1
    },
    {
        "name": "节点2",
        "childNode": [
            {
                "name": "子节点2-1",
                "childNode": [],
                "codeNumber": 1
            },
            {
                "name": "子节点2-2",
                "childNode": [],
                "codeNumber": 2
            }
        ],
        "codeNumber": 2
    },
    {
        "name": "节点3",
        "childNode": [
            {
                "name": "子节点3-1",
                "childNode": [],
                "codeNumber": 1
            }
        ],
        "codeNumber": 3
    }
]

你可能感兴趣的:(数据结构处理,javascript)