2017-01-23 13 views
1

我有這樣的數據:的Javascript得到的數據彙總成表

{ 
    "id": "123", 
    "name": "name here", 
    "thsub": { 
     "637": { 
      "id": "637", 
      "name": "Sub 1", 
      "stats": { 
       "items": 5, 
      }, 
      "ons": null 
     }, 
     "638": { 
      "id": "638", 
      "name": "Sub 2", 
      "stats": { 
       "items": 10, 
      }, 
      "ons": null 
     } 
    }, 
    "ph": 10, 
} 

這裏的是代碼:

mydata = [mydata]; 

var chList=[]; 
var thList=[]; 
var thCount=[]; 

for (var i = 0; i < mydata.length; i++) { 

    var obj = mydata[i]; 
    var cl = obj.name; 
    if (obj.thsub != null) { 
     chList.push(cl); 
    } 

    if(obj.thsub) { 
     if (i < 10) { 

      var nme = Object.keys(obj.thsub).map(function(key){ 
       var item = obj.thsub[key]; 
       return item.name; 

      }); 

      thCount.push(numberofitems); 

      thList = thList.concat(nme); 
      thCount = thCount.concat(Array(nme.length).fill(nme.length)); 

     } 
    } 
} 

我的問題是在thCount ......我需要做的是算在obj.thsub.638或其他... stats.items上的每個「項目」,並將總數放入thCount中,就像我在thList中獲得的那樣。

所以期望的結果是5和10換言之:[5,10]在這種情況下。

thCount會是[5,10]

我該怎麼做?

+0

不是很確定這個問題的問,你找誰 「統計」:{ 「項目」:5, }爲每個thsub的價值? –

+0

你的'mydata'是一個對象。它沒有「長度」。 –

+0

是的,這是正確的 – PaulTenna2000

回答

0

你應該使用鍵值訪問json對象,索引是數組。下面的代碼只是做了thcount你

 var data = { 
     "id": "123", 
     "name": "name here", 
     "thsub": { 
      "637": { 
       "id": "637", 
       "name": "Sub 1", 
       "stats": { 
        "items": 5, 
       }, 
       "ons": null 
      }, 
      "638": { 
       "id": "638", 
       "name": "Sub 2", 
       "stats": { 
        "items": 10, 
       }, 
       "ons": null 
      } 
     }, 
     "ph": 10, 
    }; 
    var thCount = []; 
    for(key in data.thsub){ 
     if(data.thsub[key].stats){ 
     thCount.push(data.thsub[key].stats.items); 
     } 
    } 
    console.log(thCount); 
0

Object.values給你一個給定對象的值列表,然後你可以在陣列中的結果地圖。在ES5:

var arr = Object.values(mydata.thsub).map(function(item) { 
    return item.stats.items 
}); 
在ES6

const list = Object.values(mydata.thsub).map(item => item.stats.items); 
0

你可以使用迭代遞歸方法用於獲取想要的值。

function getValues(object, key) { 
 

 
    function iter(o) { 
 
     if (key in o) { 
 
      result.push(o[key]); 
 
     } 
 
     Object.keys(o).forEach(function (k) { 
 
      if (o[k] && typeof o[k] === 'object') { 
 
       iter(o[k]); 
 
      } 
 
     }); 
 
    } 
 

 
    var result = []; 
 
    iter(object); 
 
    return result; 
 
} 
 

 
var data = { id: "123", name: "name here", thsub: { 637: { id: "637", name: "Sub 1", stats: { items: 5, }, ons: null }, 638: { id: "638", name: "Sub 2", stats: { items: 10, }, ons: null } }, ph: 10, }; 
 
    
 
console.log(getValues(data, 'items'));
.as-console-wrapper { max-height: 100% !important; top: 0; }