[JS] Manejo de métodos de estructura de datos anidados de varios niveles (comúnmente utilizados en el trabajo)

Este artículo continuará actualizándose, hay demasiadas cosas para entender a la vez, puede marcarlo primero, para no encontrar la dirección en el futuro o perder la última actualización.

  • Datos sin procesar:
const data = [{
    
    
	"category_name": "test",
	"children": [{
    
    
			"category_name": "test1",
			"children": [{
    
    
				"category_name": "test11",
				"children": []
			}]
		},
		{
    
    
			"category_name": "test2",
			"children": [{
    
    
				"category_name": "test21",
				"children": [{
    
    
						"tag_name": "test211",
						"tag_type": "uin"
					},
					{
    
    
						"tag_name": "test212",
						"tag_type": "fied"
					},
				]
			}]
		},
		{
    
    
			"category_name": "test3",
			"children": [{
    
    
					"tag_name": "test31",
					"tag_type": "uin"
				},
				{
    
    
					"tag_name": "test32",
					"tag_type": "tkdg"
				},
			]
		}
	]
}]

1. Filtrar los datos especificados (sin cambiar la estructura de datos original)

  • La estructura de los datos originales después del procesamiento es: (mantener solo los datos cuyo tipo de etiqueta es tipo uin)
[{
    
    
	"category_name": "test",
	"children": [{
    
    
			"category_name": "test1",
			"children": [{
    
    
				"category_name": "test11",
				"children": []
			}]
		},
		{
    
    
			"category_name": "test2",
			"children": [{
    
    
				"category_name": "test21",
				"children": [{
    
    
						"tag_name": "test211",
						"tag_type": "uin"
					},
					// {
    
    
					// 	"tag_name": "test212",
					// 	"tag_type": "fied"
					// },
				]
			}]
		},
		{
    
    
			"category_name": "test3",
			"children": [{
    
    
					"tag_name": "test31",
					"tag_type": "uin"
				},
				// {
    
    
				// 	"tag_name": "test32",
				// 	"tag_type": "tkdg"
				// },
			]
		}
	]
}]
  • Encapsulación y uso de la función de procesamiento:
/*
	children: 要递归处理的数据
	filterKey: 指定过滤的属性
	filterValue: 指定过滤的属性值
*/
function handleTagsTree(children, filterKey, filterValue) {
    
    
	  // 如果过滤的属性或属性值未指定时,直接返回原始数据
      if (!filterKey || !filterValue) {
    
    
        return children;
      }
      const data = [];
      children.forEach((item) => {
    
    
        // 如果存在 children 下一层,则递归遍历并赋值
        if (item?.children && item?.children.length !== 0) {
    
    
          item.children = handleTagsTree(item.children, filterKey, filterValue);
        }
        data.push(item);
      });
      // 添加过滤条件
      return data.filter(val => val[filterKey] === filterValue || val?.children);
}
const processedData = handleTagsTree(data, 'tag_type', 'uin')

2. Filtrar los datos especificados (mantener solo la estructura con datos)

  • La estructura de los datos originales después del procesamiento es: (mantener solo los datos cuyo tipo de etiqueta es tipo uin)
[{
    
    
	"category_name": "test",
	"children": [
		// {
    
    
		// 	"category_name": "test1",
		// 	"children": [{
    
    
		// 		"category_name": "test11",
		// 		"children": []
		// 	}]
		// 
},
		{
    
    
			"category_name": "test2",
			"children": [{
    
    
				"category_name": "test21",
				"children": [{
    
    
						"tag_name": "test211",
						"tag_type": "uin"
					},
					// {
    
    
					// 	"tag_name": "test212",
					// 	"tag_type": "fied"
					// },
				]
			}]
		},
		{
    
    
			"category_name": "test3",
			"children": [{
    
    
					"tag_name": "test31",
					"tag_type": "uin"
				},
				// {
    
    
				// 	"tag_name": "test32",
				// 	"tag_type": "tkdg"
				// },
			]
		}
	]
}]
  • Encapsulación y uso de la función de procesamiento:
/*
	children: 要递归处理的数据
	filterKey: 指定过滤的属性
	filterValue: 指定过滤的属性值
*/
function handleTagsTree(children, filterKey, filterValue) {
    
    
	  // 如果过滤的属性或属性值未指定时,直接返回原始数据
      if (!filterKey || !filterValue) {
    
    
        return children;
      }
      const data = [];
      children.forEach((item) => {
    
    
        // 如果存在 children 下一层,则递归遍历并赋值
        if (item?.children && item?.children.length !== 0) {
    
    
          item.children = handleTagsTree(item.children, filterKey, filterValue);
        }
        data.push(item);
      });
      // 添加过滤条件
      return data.filter(val => val[filterKey] === filterValue || val?.children && val.children.length);
}
const processedData = handleTagsTree(data, 'tag_type', 'uin')

3. Extraiga los datos especificados (conviértalos en una nueva matriz de salida)

  • La estructura de los datos originales después del procesamiento es: (extraer los datos de la capa tag_type para formar una nueva matriz)
[
	{
    
    
		"tag_name": "test211",
		"tag_type": "uin",
	},
	{
    
    
		"tag_name": "test212",
		"tag_type": "fied",
	},
	{
    
    
		"tag_name": "test31",
		"tag_type": "uin",
	},
	{
    
    
		"tag_name": "test32",
		"tag_type": "tkdg",
	},
]
  • Encapsulación y uso de la función de procesamiento:
/*
	children: 要递归处理的数据
	filterKey: 指定该层级特有的属性
*/
function handleTagsTree(children, filterKey) {
    
    
	if (!filterKey) {
    
    
		return children;
	}
	let data = [];
	children.forEach((item) => {
    
    
		if (item?.children && item?.children.length !== 0) {
    
    
			item = handleTagsTree(item.children, filterKey);
			data = data.concat(item);
		}
		if (item.hasOwnProperty(filterKey)) {
    
    
			data.push(item);
		}
	});
	return data;
}
const processedData = handleTagsTree(data, 'tag_name')

Supongo que te gusta

Origin blog.csdn.net/qq_45677671/article/details/131286480
Recomendado
Clasificación