本人写的一个小例子,闲话不说,上代码

		var nodes = [
			{"id":2,"cname":"第一级1","ipid":0,"ccode":"1"},
			{"id":3,"cname":"第一级1","ipid":2,"ccode":"1"},
			{"id":4,"cname":"第一级1","ipid":2,"ccode":"1"},
			{"id":5,"cname":"第一级1","ipid":4,"ccode":"1"},
			{"id":6,"cname":"第一级1","ipid":3,"ccode":"1"},
			{"id":7,"cname":"第一级1","ipid":0,"ccode":"1"}
		]		
		function transDate(list,idstr,pidstr){
			var result = [],temp = {};
			for(i = 0; i < list.length; i++){
				temp[list[i][idstr]]=list[i];//将nodes数组转成对象类型
			}
			for(j=0; j<list.length; j++){
				tempVp = temp[list[j][pidstr]]; //获取每一个子对象的父对象
				if(tempVp){//判断父对象是否存在,如果不存在直接将对象放到第一层
					if(!tempVp["nodes"]) tempVp["nodes"] = [];//如果父元素的nodes对象不存在,则创建数组
					tempVp["nodes"].push(list[j]);//将本对象压入父对象的nodes数组
				}else{
					result.push(list[j]);//将不存在父对象的对象直接放入一级目录
				}
			}
			return result;
		}
		
		console.log(transDate(nodes,"id","ipid")); //传入的值 列表 ,本对象的id,父对象的id
		document.write(JSON.stringify(transDate(nodes,"id","ipid")));


这个主要知识点就是对象的引用关系,只需要两个循环,就将列表式的结构数据,转成的树形结构。

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 2 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 4 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐