簡體   English   中英

D3 json 對數據進行排序

[英]D3 json sorts data

我正在使用以下表格讀取 json 文件

d3.json('file.json',function(error,data){
    console.log(data);
});

我希望數據按順序存儲在一個數組中(按照它存儲在原始文件中的順序),但是如果我在控制台中訪問數據,則數組條目按它們的total降序排序。 為什么會發生這種情況,我該如何避免?

[{
    "values":[...],
    "total": 6  
},
{
    "values":[...],
    "total": 45 
},
{
    "values":[...],
    "total": 100    
},
{
    "values":[...],
    "total": 40 
}]

您可以嘗試使用Array.sort()對數組進行排序以達到您想要的結果。

例如,如果您希望根據total屬性按升序排列,

 const input = [{ "values":[], "total": 6 }, { "values":[], "total": 45 }, { "values":[], "total": 100 }, { "values":[], "total": 40 }]; const res = input.sort((a, b) => a.total - b.total); console.log(res);

這就是您可以使用 d3 代碼實現排序的方式。

d3.json('file.json',function(error, data){
  const res = data.sort((a, b) => a.total - b.total);
  // render graph
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM