一个数组处理合并问题,半天没弄出来想要的结果

2018-05-23 13:47:16 +08:00
 leega0

经过操作产生以下数组

var arr = [
{"pid":"12dassdf",
"source":{"id":"sd1a3","component":"ordinary"},
"target":{"id":"sdbf3","component":"ordinary"}
},
{"pid":"ccdassdf",
"source":{"id":"sd123","component":"start"},
"target":{"id":"sd1a3","component":"ordinary"}
},
{"pid":"1gdassdf",
"source":{"id":"er12a","component":"ordinary"},
"target":{"id":"sdop3","component":"end"}
},
{"pid":"62dayhdf",
"source":{"id":"sdbf3","component":"ordinary"},
"target":{"id":"sd3bn","component":"ordinary"}
},
{"pid":"7udassdf",
"source":{"id":"sd3bn","component":"block"},
"target":{"id":"er12a","component":"ordinary","arclist":{"nodes":[{"pid":"结构同上"},...]}}
},
]

求最后生成一个,start 开头的对象顺序数组:

var newarr = [{"id":"sd123","component":"start"},
{"id":"sd1a3","component":"ordinary"},
...,{"id":"sdop3","component":"end"}]

本来以为很简单的,找到 start 那组,拿到 target,然后根据 target 的 id,去循环匹配 source 的 id,push 到空数组。

可是实际编码中,普通 for 循环只找打第一个就停止了,再加上还有内部嵌套,又加了个递归,一试就变成了死循环。

1310 次点击
所在节点    前端开发
5 条回复
jasperjia
2018-05-23 16:25:51 +08:00
在用 G6 做网图吗,手动滑稽
jasperjia
2018-05-23 16:28:34 +08:00
我的做法,参照你的话就是,先循环取出所有 id,再根据前序-后续关系对所有 id 进行排序
leega0
2018-05-23 17:00:48 +08:00
@jasperjia 用的 d3,现在难点就是前序-后序的关联,感谢指点,我去试试
leega0
2018-05-23 18:24:10 +08:00
此问题终结,用了冒泡排序解决。
changnet
2018-05-23 19:00:10 +08:00
循环一次,把它们都扔到 kv 结构,同时找出 start。再循环一次,把它们放到数组。

如果你的 id 都是增长的,不就一简单排序么

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/457123

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX