SOURCE

let nodeList = [
	{
		id: "1",
		outputId: "rPbRTXIlaaHD",
	},
	{
		id: "2",
		outputList: [
			{
				id: "qTqbarecivyM",
			},
		],
		inputId: "dqgrvUfNzpJv",
		outputId: "KeHPmXoqkppY",
	},
	{
		id: "2-1",
		inputId: "afUhvDjZNzRl",
		outputId: "lmOJwfrReUoo",
	},
	{
		id: "2-2",
		outputList: [
			{
				id: "gOBbnkcdRvBE",
			},
		],
		inputId: "vVhDJThlcTOA",
		outputId: "WxePOWWNLkty",
	},
	{
		id: "2-2-1",
		inputId: "hQQHTZRHHZPW",
		outputId: "etYftlEuQvcw",
	},
]

const relationshipList = [
	{
		type: "relationship",
		text: "1 关联 2",
		source: "rPbRTXIlaaHD",
		target: "dqgrvUfNzpJv",
	},
	{
		type: "relationship",
		text: "2 关联 2-1",
		source: "qTqbarecivyM",
		target: "afUhvDjZNzRl",
	},
	{
		text: "2-1 关联 2-2",
		type: "relationship",
		source: "lmOJwfrReUoo",
		target: "vVhDJThlcTOA",
	},
	{
		text: "2-2 关联 2-2-1",
		type: "relationship",
		source: "gOBbnkcdRvBE",
		target: "hQQHTZRHHZPW",
	},
]

const startNode = nodeList.shift()
let nextObj = startNode

let resList = [startNode]

const fun = function (id,parentId) {
	for (let node of nodeList) {
		const edge = relationshipList.find((j) => j.source === id)
		if (!edge) continue
    if (node.inputId !== edge.target) continue

  
    if(parentId){
      node.parentId = parentId
    }
    console.log('node',node)
    console.log('parentId',parentId)
 
		const outputList = node.outputList || []
		for (let item of outputList) {
        fun(item.id,node.id)
		}

    fun(node.outputId,parentId)
    
    resList.push(node)
	}
}

fun(startNode.outputId)

console.log('resList',resList)


function listToTree(data) {
    const map = {};
    const tree = [];

    // Create a map of all items
    data.forEach(item => {
        map[item.id] = { ...item, children: [] };
    });

    // Iterate through the items and arrange them into the tree
    data.forEach(item => {
        if (item.parentId) {
            map[item.parentId].children.push(map[item.id]);
        } else {
            tree.push(map[item.id]);
        }
    });

    return tree;
}

console.log('转为树',listToTree(resList))

// 预期
let expect = [
	{
		id: "1",
		outputId: "rPbRTXIlaaHD",
	},
	{
		id: "2",
		inputId: "dqgrvUfNzpJv",
		outputId: "KeHPmXoqkppY",
		outputList: [
			{
				id: "qTqbarecivyM",
			},
		],
		children: [
			{
				id: "2-1",
				inputId: "afUhvDjZNzRl",
				outputId: "lmOJwfrReUoo",
			},
			{
				id: "2-2",
				inputId: "vVhDJThlcTOA",
				outputId: "WxePOWWNLkty",
				outputList: [
					{
						id: "gOBbnkcdRvBE",
					},
				],
				children: [
					{
						id: "2-2-1",
						inputId: "hQQHTZRHHZPW",
						outputId: "etYftlEuQvcw",
					},
				],
			},
		],
	},
]
console 命令行工具 X clear

                    
>
console