慕运维8079593
const data = [ { target: 'a', source: 'a' } , { target: 'a', source: 'b' } , { target: 'b', source: 'c' } , { target: 'c', source: 'd' } ];let CurKey = '', CurrentChild = null, result = null; data.forEach( elm => { if (elm.target === elm.source) { CurKey = elm.target; result = { "target": CurKey, "children": [] }; CurrentChild = result.children; } else if (elm.target === CurKey) { CurKey = elm.source; if (data.findIndex(ef=>ef.target===elm.source) >0 ) { let newElm = { "target": CurKey, "children": [] }; CurrentChild.push(newElm) CurrentChild = newElm.children; } else { let newElm = { "target": CurKey }; CurrentChild.push(newElm) CurrentChild = null; CurKey = null; } }});console.log(JSON.stringify(result));Second Case, without { target: 'a', source: 'a' } :const data = [ { target: 'a', source: 'b' } , { target: 'b', source: 'c' } , { target: 'c', source: 'd' } ];let CurKey = '', CurrentChild = null, result = null; data.forEach( elm => { if (CurKey === '') { CurKey = elm.target; result = { "target": CurKey, "children": [] }; CurrentChild = result.children; } if (elm.target === CurKey) { CurKey = elm.source; if (data.findIndex(ef=>ef.target===elm.source) >0 ) { let newElm = { "target": CurKey, "children": [] }; CurrentChild.push(newElm) CurrentChild = newElm.children; } else { let newElm = { "target": CurKey }; CurrentChild.push(newElm) CurrentChild = null; CurKey = null; } }});console.log(JSON.stringify(result));Second Case, without { target: 'a', source: 'a' } :const data = [ { target: 'a', source: 'b' } , { target: 'b', source: 'c' } , { target: 'c', source: 'd' } ];let CurKey = '', CurrentChild = null, result = null; data.forEach( elm => { if (CurKey === '') { CurKey = elm.target; result = { "target": CurKey, "children": [] }; CurrentChild = result.children; } if (elm.target === CurKey) { CurKey = elm.source; if (data.findIndex(ef=>ef.target===elm.source) >0 ) { let newElm = { "target": CurKey, "children": [] }; CurrentChild.push(newElm) CurrentChild = newElm.children; } else { let newElm = { "target": CurKey }; CurrentChild.push(newElm) CurrentChild = null; CurKey = null; } }});console.log(JSON.stringify(result));Second Case, without { target: 'a', source: 'a' } :const data = [ { target: 'a', source: 'b' } , { target: 'b', source: 'c' } , { target: 'c', source: 'd' } ];let CurKey = '', CurrentChild = null, result = null; data.forEach( elm => { if (CurKey === '') { CurKey = elm.target; result = { "target": CurKey, "children": [] }; CurrentChild = result.children; } if (elm.target === CurKey) { CurKey = elm.source; if (data.findIndex(ef=>ef.target===elm.source) >0 ) { let newElm = { "target": CurKey, "children": [] }; CurrentChild.push(newElm) CurrentChild = newElm.children; } else { let newElm = { "target": CurKey }; CurrentChild.push(newElm) CurrentChild = null; CurKey = null; } }});console.log(JSON.stringify(result));