我不想通過比較每個數組中的兩個字段來連接兩個json數組(如SQL連接:請參閱代碼中的if),並將第二個數組中的值添加到第一陣列。我嘗試通過使用嵌套循環來解決此問題,並將內部循環的值傳遞給外部循環(請參閱代碼)。但結果是alwayś0.通過比較兩個鍵來連接兩個json數組
曼尼謝謝!
下面是代碼示例:
var dmNodeGraph = [ { id: 'marathonschaatsteams',
group: '9',
type: 'child',
color: '33cccc' },
{ id: 'KNSB', group: '9', type: 'child', color: '33cccc' },
{ id: 'stationshuisje',
group: '9',
type: 'child',
color: '33cccc' },
{ id: 'RTV', group: '9', type: 'child', color: '33cccc' },
{ id: 'wachten', group: '5', type: 'child', color: '99cc00' },
{ id: 'smartcards', group: '9', type: 'child', color: '33cccc' } ]
var groupByLink = [ { key: 'stationshuisje-kpn-9', values: 1 },
{ key: 'RTV-tele2-9', values: 14 },
{ key: 'Spelen-kpn-9', values: 13 },
{ key: 'hoofdsponsor-kpn-9', values: 14 },
{ key: 'schaatsen-kpn-9', values: 13 },
{ key: 'KNSB-kpn-9', values: 17 },
{ key: 'klanten-ziggo-9', values: 3 },
{ key: 'kaarten-ziggo-9', values: 1 },
{ key: 'wachten-ziggo-9', values: 1 },
{ key: 'marathonschaatsteams-kpn-9', values: 1 },
{ key: 'wachten-tele2-9', values: 1 },
{ key: 'gebruiken-kpn-9', values: 1 },
{ key: 'wachten-kpn-9', values: 1 },
{ key: 'abonnementen-kpn-9', values: 2 },
{ key: 'wachten-Glasvezel-5', values: 1 },
{ key: 'smartcards-ziggo-9', values: 2 } ]
$('#test').append('This is from the loop <br>')
for (var i = 0; i < dmNodeGraph.length; i++){
var id = dmNodeGraph[i].id
var group = dmNodeGraph[i].group
var value
//$('#test').append('<br> ------------------- id: ' + id + ' group: ' + group + '--------------------' )
// 4.A.1.A Loop per Node through the grouped links
for (var gl = 0 ; gl < groupByLink.length ; gl++){
//value = 0
var keys = groupByLink[gl].key.split('-')
if (keys[0] == id && keys[2] == group){
value = groupByLink[gl].values
// Location A
//$('#test').append('<br> id: ' + id + ' group: ' + group + ' values: ' + value)
}
}
// Location B
dmNodeGraph[i].values = value
$('#test').append('<br> id: ' + id + ' group: ' + group + ' values: ' + value)
}
的代碼示例也可在jsFidle(https://jsfiddle.net/L67nwzs0/22/)
[在到一個陣列合併兩個JSON/JavaScript數組]的可能的複製(http://stackoverflow.com/questions/ 10384845/merge-two-json-javascript-arrays-in-to-one-array) – Pete
刪除值= 0,在循環的最後一次迭代中使其爲零。在你聲明var value = 0的地方進行初始化; – softwarenewbie7331