js 常用处理数据方法

112 阅读2分钟

js 数组合并根据id去重,id相同使用后一个数组数据

const mergeAndUniqueById = (arr1, arr2) => {

    // 先将第二个数组合并到第一个数组

    arr1.push(...arr2);

    // 使用reduce方法去重并更新数据

    return arr1.reduce((acc, current) => {

        const foundIndex = acc.findIndex(item => item.id === current.id);

        if (foundIndex === -1) {

            acc.push(current);

        } else {

            acc[foundIndex] = current;

        }

        return acc;

    }, []);

};

// 示例数据

const arr1 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];

const arr2 = [{ id: 1, name: 'Charlie' }, { id: 3, name: 'David' }];

// 使用函数

const result = mergeAndUniqueById(arr1, arr2);

console.log(result);

// 输出: [{ id: 1, name: 'Charlie' }, { id: 2, name: 'Bob' }, { id: 3, name: 'David' }]

树形数据:找到没有子集的第一项数据

const tree = [
      {
        name: 'root',
        children: [
          {
            name: 'child1',
            children: [
              {
                name: 'grandchild1',
                children: []
              }
            ]
          },
          {
            name: 'child2',
            children: []
          }
        ]
      }
    ];

    // 找到没有子集的第一项数据
    function getFirstLeafNode(tree) {
      let firstLeaf = null;
      let index = 0;

      function traverse(nodes, currentIndex) {
        if (!nodes || nodes.length === 0) return;
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i];
          if (node.children && node.children.length > 0) {
            traverse(node.children, currentIndex + '.' + i);
          } else {
            if (!firstLeaf) {
              firstLeaf = { node, index: currentIndex + '.' + i };
            }
          }
        }
      }

      traverse(tree, '0');
      return firstLeaf ? firstLeaf.node : null;
    }

    const firstLeafNode = getFirstLeafNode(tree);
    console.log(firstLeafNode); // 输出没有子集的第一项数据
    // {name: "grandchild1", children: Array(0)}

树形数据:指定节点插入数据

方法1

// 定义树形数据结构
let treeData = [
  {
	id: 1,
	name: 'Node 1',
	children: [
	  {
		id: 2,
		name: 'Node 1.1'
	  }
	]
  },
  {
	id: 3,
	name: 'Node 2',
	children: []
  }
];

// 插入新节点的函数
function insertNode(tree, newNode, parentId, props = {}) {
  let key = props.key || "id";
  let children = props.children || "children";
  
  const findNode = (nodes, id) => {
	for (let node of nodes) {
	  if (node[key] === id) {
		return node;
	  }
	  if (node[children] && node[children].length > 0) {
		let found = findNode(node[children], id);
		if (found) return found;
	  }
	}
	return null;
  };

  const addChild = (node, newNode) => {
	if (node[children]) {
		node[children].push(newNode);
	} else {
		node[children] = [newNode];
	}
	
  };

  const parent = findNode(tree, parentId);
  if (parent) {
	addChild(parent, newNode);
  } else {
	tree.push(newNode); // 如果没有找到父节点,添加到根节点
  }
}

// 插入新节点
insertNode(treeData, { id: 4, name: 'Node 1.2', children: [] }, 3);

console.log(JSON.stringify(treeData, null, 2));

方法2

let data = [
    {
        id: 1,
        label: '一级 1',
        children: [
            {

                id: 4,
                label: '二级 1-1',
                children: [
                    {

                        id: 9,
                        label: '三级 1-1-1'
                    }, 
                    {

                        id: 10,
                        label: '三级 1-1-2'
                    },
                ]
            },
        ]
    },
    {
        id: 11,
        label: '一级 2',
    }
]
const appendNodeInTree = (id, tree, obj) => {

    tree.forEach(ele=> {

        if (ele.id === id) {

            ele.children ? ele.children.push(obj) : ele.children = [obj]
        } else {

          if (ele.children) {

              appendNodeInTree(id, ele.children, obj)
          }
        }
    })
    return tree
}
appendNodeInTree(0, data, {
	id: 13,
	label: '三级 1-1-3',
})
console.log(JSON.stringify(data, null, 2));

树形数据循环处理数据

// 例子是把childrenList修改为children
findChildren(list) {
    return list.reduce((pre: any, item: any) => {
        if (item.childrenList.length) {
            item.children = this.findChildren(item.childrenList)
        }

        delete item.childrenList

        pre.push(item)
        return pre
    }, [])
}