2015-11-24 47 views
0

我正在根據我擁有的CSV文件生成JavaScript對象。根據對象值將名稱添加到對象

這裏是對象當前如下like--對象的數組:

 [ 
     { 
     "country": "afghanistan", 
     "iso3": "afg", 
     "first_characteristic": 3, 
     "second_characteristic": 5, 
     "third_characteristic": 3 
     }, 
     { 
     "country": "united states", 
     "iso3": "usa", 
     "first_characteristic": 8, 
     "second_characteristic": 6, 
     "third_characteristic": 7 
     }, 
     { 
     "country": "china", 
     "iso3": "chn", 
     "first_characteristic": 6, 
     "second_characteristic": 0.7, 
     "third_characteristic": 2 
     } 
    ] 

The fiddle is here

我想爲每個對象添加一個名稱,該名稱是從其中一個值派生的,並且輸出爲嵌套對象。

原來這就是我想要的新對象的樣子:

{ 
     "afg":{ 
     "country": "afghanistan", 
     "iso3": "afg", 
     "first_indicator": 3, 
     "second_indicator": 5, 
     "third_indicator": 3 
     }, 
     "usa":{ 
     "country": "united states", 
     "iso3": "usa", 
     "first_indicator": 8, 
     "second_indicator": 6, 
     "third_indicator": 7 
     }, 
     "chn":{ 
     "country": "china", 
     "iso3": "chn", 
     "first_indicator": 6, 
     "second_indicator": 0.7, 
     "third_indicator": 2 
     } 
    } 

我無法弄清楚如何添加這些名字。任何幫助是極大的讚賞。

+1

請注意'[富數據: bar,fizz:buzz]在_JavaScript_中不是有效的_Array_。你是說你想要索引和鍵嗎?只是鑰匙?只是標記,但標籤以某種方式連接? –

+0

@Paul S.更新 – sprucegoose

+0

您的目標json看起來不正確,因爲數組中的每個元素的格式爲「」...「:{...}'。是否需要它是一個數組,它可能是一個對象嗎? – Romski

回答

2

在一條線使用ES6,其中arr是作爲陣列obj是導致對象

var obj = arr.reduce((o, e) => ((o[e.iso3] = e), o), {}); 
0

試試這個,

function setNameToJSONObj(json){ 

    var rslt = []; 

    for(var i = 0; i< json.length; i++){ 
    rslt[json[i].iso3] = json[i]; 
    } 
    return rslt; 
} 
+0

謝謝,這也有幫助! – sprucegoose