2015-05-15 62 views
0

檢索的JSON一個獨特的密鑰的所有值

var data = 

[ 
    { 
     "id":"07907313", 
     "type":"car", 
     "year":"1999" 
    }, 
    { 
     "id":"0797096", 
     "type":"boat", 
     "year":"2013" 
    }, 
    { 
     "id":"2341353", 
     "type":"plane", 
     "year":"2015" 
    } 
] 

我做

var jsonAsString = JSON.stringify(data); 
var jsonData = JSON.parse(jsonAsString); 

我想拔出每一個獨特的密鑰(ID,類型,年份)值,並創建另一個變種與格式:

[ 
    {"name": "id", "data": ["07907313","0797096","2341353"]}, 
    {"name": "type", "data": ["car","boat","plane"]}, 
    {"name": "year", "data":["1999","2013","2015"]} 
] 

我一直在努力獲得我想要的輸出。任何幫助將不勝感激。

+0

您只需要輸出中的unqiue值? – thefourtheye

回答

1

您想先從現在的每個項目開始,提取數據並將其合併到單個對象中。事情是這樣:

var data = [{ 
 
    "id": "07907313", 
 
    "type": "car", 
 
    "year": "1999" 
 
}, { 
 
    "id": "0797096", 
 
    "type": "boat", 
 
    "year": "2013" 
 
}, { 
 
    "id": "2341353", 
 
    "type": "plane", 
 
    "year": "2015" 
 
}]; 
 

 
var results = {}; 
 

 
data.forEach(function(item) { 
 
    Object.keys(item).forEach(function(key) { 
 
    results[key] = results[key] || []; 
 
    results[key].push(item[key]); 
 
    }); 
 
}); 
 

 
document.getElementById('r').textContent = JSON.stringify(results);
<pre id="r"></pre>

+0

謝謝ssube!這很好地獲取所需格式的數據。我能夠使用你的代碼,並按照以下格式推送值:finalArray.push({「name」:key,「data」:results [key]});謝謝你的幫助! – tblack06

相關問題