2016-02-08 64 views
1

我嵌套我的數據是這樣如何訪問嵌套的數據值D3

var nested_data = d3.nest() 
    .key(function(d) { return d.Country; }) 
    .entries(CSV); 

,並已發現,當我綁定數據我可以使用數組的值,如果我用這個功能

name.selectAll('.name') 
    .data(function(d) { 
     return d.values; <--- Accesses the nested data 
    }) 
    .text(function(d) { 
     return d.Name;  <--- Nested value 
    }) 

但是我在我的項目的其他地方遇到了麻煩。另一個我需要的嵌套值是一個名爲['starting point']的字符串。我怎樣才能訪問這個值在這個d3.filter()例如?

var filter = nested_data.filter(function(d) { 
    return ("Island" == d['starting point']) 
}); 

我想嘗試:d.values [ '起點']

或者甚至創建一個新的變量

變種nested_values = nested_data(函數(d){返回d。值});

但沒有一個是有效的。我應該在這裏做什麼?

回答

0

可以在這樣的嵌套數據篩選數據:

nested_data.map(function(m) { 
    //for each group do the filter on each value 
    m.values = m.values.filter(function(d) { 
    //return true for those having starting point as island. 
    return d['starting point'] == 'Island'; 
    }) 
}) 

工作代碼here

+0

我沒想到的是,再次感謝。我發現很難找到這方面的例子。我可以做什麼,當我再次遇到這個: nested_data.forEach(函數(d){ if(uniqueLocations.indexOf(d ['starting point'])<0) uniqueLocations.push(d ['起點']) }); – user3821345

+0

做這樣的事'var unique = []; nested_data.map(函數(M){ m.values.forEach(函數(d){ \t如果(unique.indexOf(d [ '起點'])<0) \t unique.push(d [」起點']); //添加自從不存在於數組 }) }) ' 這裏提琴https://jsfiddle.net/cyril123/jp90dssj/2/ – Cyril

+1

我要讀更多關於d3.map()。再次感謝 – user3821345