2017-05-03 80 views
0

我目前正在開發一個使用JSON文件的小應用程序。我的數據有問題。我必須過濾我的數據。例如,我想要某個用戶ID的所有數據,但我不知道如何做到這一點。 這裏是我的JSON文件的例子:過濾JSON文件中的數據

[{ 
    "ConsoPhot_Id": "7924", 
    "idLotImport": 166, 
    "Date_Id": 20160601, 
    "Orga_Id": "86094", 
    "NbTache": 35, 
    "NbCopie": 143, 
    "NbCopieBW": 56, 
    "NbCopieCouleur": 87, 
    "MtTotal": 3.53 
}, 
{ 
    "ConsoPhot_Id": "7925", 
    "idLotImport": 166, 
    "Date_Id": 20160601, 
    "Orga_Id": "86537", 
    "NbTache": 291, 
    "NbCopie": 969, 
    "NbCopieBW": 622, 
    "NbCopieCouleur": 347, 
    "MtTotal": 15.61 
}, 
{ 
    "ConsoPhot_Id": "7926", 
    "idLotImport": 166, 
    "Date_Id": 20160601, 
    "Orga_Id": "86386", 
    "NbTache": 7, 
    "NbCopie": 32, 
    "NbCopieBW": 31, 
    "NbCopieCouleur": 1, 
    "MtTotal": 0.16 
}, 
{ 
    "ConsoPhot_Id": "7927", 
    "idLotImport": 166, 
    "Date_Id": 20160601, 
    "Orga_Id": "86084", 
    "NbTache": 2, 
    "NbCopie": 3, 
    "NbCopieBW": 3, 
    "NbCopieCouleur": 0, 
    "MtTotal": 0.01 
}, 
{ 
    "ConsoPhot_Id": "7928", 
    "idLotImport": 166, 
    "Date_Id": 20160701, 
    "Orga_Id": "86094", 
    "NbTache": 33, 
    "NbCopie": 68, 
    "NbCopieBW": 31, 
    "NbCopieCouleur": 37, 
    "MtTotal": 1.53 
}, 

例如,我要爲Orga_Id:在JSON文件「86094」中的所有數據。我唯一能做的事情就是把所有的數據與此例如:

d3.json("Data.json", function(error, data) { 
    var NbCopie = data.map(function(d) { 
     return d.NbCopie; 
    }); 

回答

1

您可以使用Array#filter()

下面的代碼在ES6

const data =[{"ConsoPhot_Id":"7924","idLotImport":166,"Date_Id":20160601,"Orga_Id":"86094","NbTache":35,"NbCopie":143,"NbCopieBW":56,"NbCopieCouleur":87,"MtTotal":3.53},{"ConsoPhot_Id":"7925","idLotImport":166,"Date_Id":20160601,"Orga_Id":"86537","NbTache":291,"NbCopie":969,"NbCopieBW":622,"NbCopieCouleur":347,"MtTotal":15.61},{"ConsoPhot_Id":"7926","idLotImport":166,"Date_Id":20160601,"Orga_Id":"86386","NbTache":7,"NbCopie":32,"NbCopieBW":31,"NbCopieCouleur":1,"MtTotal":0.16},{"ConsoPhot_Id":"7927","idLotImport":166,"Date_Id":20160601,"Orga_Id":"86084","NbTache":2,"NbCopie":3,"NbCopieBW":3,"NbCopieCouleur":0,"MtTotal":0.01},{"ConsoPhot_Id":"7928","idLotImport":166,"Date_Id":20160701,"Orga_Id":"86094","NbTache":33,"NbCopie":68,"NbCopieBW":31,"NbCopieCouleur":37,"MtTotal":1.53}]; 
 

 
const key = "Orga_Id"; 
 
const value= "86094"; 
 
const result = data.filter(d=>d[key]==value); 
 

 
console.log(result);

+0

好這是偉大的,但只是一個澄清,我的JSON文件是非常巨大的(42802線)存在ES6另一種解決方案比「數據常量」像JSON.read或類似的東西?謝謝。 –

+0

你可以在你提供的代碼'd3.json('Data.json',函數(e,data){data.filter(...)}'中的代碼' – Weedoze

+0

@Downvoter爲什麼? – Weedoze

2

可以做本地陣列方法的濾鏡陣列Array.filter

 var NbCopie = data.filter(function(value) { 
      return value.Orga_Id == "86094"; 
    }); 
0

您可以使用jQuery的相同這樣

**$.each(data, function (i, data) { 
       if (data.Orga_Id == "86094") 
       //then the data; 
      });**