在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ js數(shù)組對象的清洗組合操作

js數(shù)組對象的清洗組合操作

經(jīng)過操作產(chǎn)生以下數(shù)組

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":"結(jié)構(gòu)同上"},...]}}
},
]

求最后生成一個,start 開頭的對象順序數(shù)組:

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

本來以為很簡單的,找到 start 那組,拿到 target,然后根據(jù) target 的 id,去循環(huán)匹配 source 的 id,push 到空數(shù)組。

可是實際編碼中,普通 for 循環(huán)只找打第一個就停止了,再加上還有內(nèi)部嵌套,又加了個遞歸,一試就變成了死循環(huán)

回答
編輯回答
話寡

不知道是不是這個意思,沒有對arclist進行處理,如果需要的話,可以對node執(zhí)行一下recursion

function sortStart(arr) {
  var origin = arr
  var result = []
  var start =origin.filter(item => item.source.component === 'start')[0]
  result.push(start.source)
  recursion(origin, start, result)
  return result
}
function recursion(origin, start, result) {
  if (start.source.component === 'end') {
      result.push(start.source)
      return result
  }
  start = origin.filter(item => start.target.id === item.source.id)[0]
  result.push(start.source)
  if (start.target.component === 'end') {
    result.push(start.target)
    return result
  } else {
    recursion(origin, start, result)
  }
}

[ { id: 'sd123', component: 'start' },
  { id: 'sd1a3', component: 'ordinary' },
  { id: 'sdbf3', component: 'ordinary' },
  { id: 'sd3bn', component: 'block' },
  { id: 'er12a', component: 'ordinary' },
  { id: 'sdop3', component: 'end' } ]
2017年10月17日 03:02
編輯回答
痞性

你的第一項的兩個component都是ordinary

2017年5月24日 03:37
編輯回答
夢囈

思路供參考

const sourceMap = new Map(arr.map(x => ([x.source.id, { visited: false, data: x }])))

let it = arr.find(x => x.source.component === 'start')

const result = [it.source]

while (it.target.component !== 'end') {
  const o = sourceMap.get(it.target.id)
  if (o.visited) { throw new Error('dead loop :', data) }
  o.visited = true
  it = o.data
  result.push(it.target)
}

console.log(result)
2017年6月13日 11:18