单属性的转换阵列JavaScript对象以键/值对

单属性的转换阵列JavaScript对象以键/值对

问题描述:

的阵列我有一个看起来像单属性的转换阵列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

由于全部改造的元件中发生的事情,我喜欢用[] .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"}] 

通过你的字典里只是环和到位修改每一个元素:

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 }; 
} 

这不是最优雅的解决方案,但它的工作原理。

您可以使用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"}] 

下面是一个使用简单的解决方案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/