2014-09-05 104 views
0

的陣列我有一個看起來像單屬性的轉換陣列JavaScript對象以鍵/值對

my_dictionary = [ 
    {"first_thing": "1"}, 
    {"second_thing": "2"} 
] 

,但JavaScript的字典集合需要像

my_dictionary = [ 
    {key: "first_thing", value: "1"}, 
    {key: "second_thing", value: "2"} 
] 

。由於這些字典中有這麼多,我需要一種方法來遍歷它們並更改所有的字典,以便它們將內部keyvalue

我試過迭代,並嘗試使用類似my_dictionary[0].key以及my_dictionary[0][0]的選擇它們,我希望它能工作,但我想這不是做到這一點的方法。

+0

...爲什麼不只是'{first_thing:1,second_thing:2}'?爲什麼這個單一屬性對象的數組? – meagar 2014-09-05 20:00:27

回答

2

由於全部改造的元件中發生的事情,我喜歡用[] .MAP()這個:

[{"first_thing": "1"}, {"second_thing":"2"}].map(function(o){ 
    var o2={}; 
    Object.keys(o).forEach(function(k){o2.key=k; o2.value=o[k];}); 
    return o2; 
}); 

// == [{"key":"first_thing","value":"1"},{"key":"second_thing","value":"2"}] 
0

通過你的字典裏只是環和到位修改每一個元素:

for (var index = 0; index < my_dictionary.length; index++) { 
    var element = my_dictionary[index], 
     key, value; 

    // Grab the initial element 
    for (var tempKey in element) { 
     if (element.hasOwnProperty(tempKey)) { 
      key = tempKey; 
      value = element[tempKey]; 
      break; 
     } 
    } 

    // Reset the element 
    element = { "key": key, "value": value }; 
} 

這不是最優雅的解決方案,但它的工作原理。

-1

您可以使用for..in

無副作用

var dict_in = [{"first_thing": "1"}, {"second_thing": "2"}]; 

var dict_out = (function (arr) { 
    var d = [], i, k; 
    d.length = arr.length; 
    for (i = 0; i < arr.length; ++i) 
     for (k in arr[i]) { 
      d[i] = {'key': k, 'value': arr[i][k]}; 
      break; 
     } 
    return d; 
}(dict_in)); 

dict_out; // [{key: "first_thing", value: "1"}, {key: "second_thing", value: "2"}] 

副作用

var dict_in = [{"first_thing": "1"}, {"second_thing": "2"}]; 

(function (arr) { 
    var i, k, v; 
    for (i = 0; i < arr.length; ++i) 
     for (k in arr[i]) { 
      v = arr[i][k]; 
      delete arr[i][k]; 
      arr[i].key = k; 
      arr[i].value = v; 
      break; 
     } 
    return arr; 
}(dict_in)); // [{key: "first_thing", value: "1"}, {key: "second_thing", value: "2"}] 
0

下面是一個使用簡單的解決方案jQuery.each()

var result = []; 
var my_dictionary = [{"first_thing": "1"}, {"second_thing":"2"}]; 
$.each(my_dictionary, function(index, element) { 
    $.each(element, function(key, value) { 
     result.push({"key" : key, "value" : value}); 
    }); 
}); 

小提琴在這裏:http://jsfiddle.net/36o170w9/

相關問題