2017-02-23 27 views
0

最近我開始使用D3.js繪製曬傷圖。數據以JSON提供。對於一些設計的東西,我想交換一些項目(在D3文檔中稱爲兒童)。 我知道JS數組是對象,所以是這樣的:不可變陣列的問題

var buffer = myarray[2]; 

只是一個參考。因此交換緩衝區沒有效果(?)。 因此,我發明了第二個數組(childrens_final)在我的代碼中採用了交換過程中的項目。它只是迭代每個項目,第二個迭代是查找具有相同名稱的項目以連續設置具有相同名稱的項目。因此交換。

var childrens = response_data.data.data['children']; 
var childrens_final = [] 
for (var child = 0; child < childrens.length; child++) { 
    var category = childrens[child]; 
    var found = false; 
    var i = child+1 
    while (!(found) && (i < childrens.length)) { 
     if (childrens[i]['name'] == category['name']) { 
      var childrens = swapArrayElements(childrens, child+1, i); 
      var one = childrens[child]; 
      var two = childrens[child+1] 
      found = true; 
      } 
      i++; 
      } 
      if (found) { 
       childrens_final.push(one); 
       childrens_final.push(two); 
       child++; 
      } 
      else { 
       childrens_final.push(childrens[child]) 
      } 
     } 
response.data.data['children'] = childrens_final; 
return response.data.data; 

函數swapArrayElements()是在運用剪接:

function swapArrayElements(list, x, y) { 
    if (list.length ==1) return list; 
    list.splice(x, 1, list.splice(y,1, list[x])[0]); 
    return list; 
} 

的問題是,仍沒有從圖中的交換作用。但是在記錄childrens_final時。在控制檯中有這樣的東西:

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object ] 

對象是在正確的順序!但在陣列中仍然存在舊秩序。 這實際上是如此基本,但我沒有看到一個解決方案。

Btw ...該代碼在AngularJS下工作。

+0

你有樣品數據來運行這個? – gotomanners

+0

是啊當然... https://jsfiddle.net/b2b6n78e/ 對不起...沒有找到一個更好的方式來存儲它 – foxmulder

回答

1

發現問題。這是一個D3.js問題。 D3正在整理數據本身。您必須明確設置:

d3.layout.partition.sort(null) 

否則,每個預先排序過程都不起作用。

+0

找到這[鏈接佈局](https://github.com/d3 /d3-3.x-api-reference/blob/master/Partition-Layout.md)。有一個函數.sort()可以設置爲null。如果不是默認值是降序。 但是你是對的。函數是d3.layout.partition.sort()。 – foxmulder