把json中的对象按从from到to的顺序排序
程序员文章站
2022-06-10 18:19:24
...
<script> //把数据中的对象按从from到to的顺序排序 var jsonArray = [{"FROM":"NODES_11","TO":"22"},{"FROM":"22","TO":"NODES_3"},{"FROM":"NODES_3","TO":"NODES_2"},{"FROM":"NODES_0","TO":"NODES_11"}]; var newArray = []; //用来存在排序后的数据 debugger; //js调试断点 getTo("NODES_0"); //递归调用 debugger; function getTo(NODES_0) { for (var i = 0 ; i < jsonArray.length; i++) { if (jsonArray[i].FROM == NODES_0) //nodes_0固定排第一位 { newArray.push(jsonArray[i]); //放入新数组中 var jsonArrayTo = jsonArray[i].TO; //根据to找下一个 jsonArray.splice(i,1); //移除已经排序的 i--; getTo(jsonArrayTo); } } } //结果为 newArray=[{"FROM":"NODES_0","TO":"NODES_11"},{"FROM":"NODES_11","TO":"22"},{"FROM":"22","TO":"NODES_3"},{"FROM":"NODES_3","TO":"NODES_2"}]; </script>