简体   繁体   English

javascript中具有键值对的数组中的键值对

[英]Key Value pair from an array with key Value pair in javascript

I have an array like this: 我有一个像这样的数组:

var arrayTemp = [
{"0":["Z",59]},
{"1":["D",53]},
{"2":["6",26]},
{"3":["3",19]},
{"4":["Y",10]},
{"5":["H",7]},
{"6":["G",5]},
{"7":["2",5]}
];

I need an output similar to the below one, 我需要类似下面的输出,

var arrayTemp = [
{"Z":59},
{"D":53},
{"6":26},
{"3":19},
{"Y":10},
{"H":7},
{"G":5},
{"2":5}
];

How do I achieve this? 我该如何实现? I would like this to be achieved with the help of json, underscore or JavaScript. 我希望在json,下划线或JavaScript的帮助下实现这一目标。

Using Array.prototype.map() you could iterate trough each element of the original array and create the required objects, returning them as new elements in a new array. 使用Array.prototype.map()可以遍历原始数组的每个元素并创建所需的对象,并将它们作为新元素返回到新数组中。

var newArray = arrayTemp.map(function(e, index) { 
    var x = {};
    x[e[index][0]] = e[index][1];

    return x;
})

DEMO - Using Array.prototype.map() to create the new array 演示 -使用Array.prototype.map()创建新数组


Something like this: 像这样:

var newArray = arrayTemp.map(function(e) { 
    var index = Object.keys(e).shift(),
        innerElement = e[index],
        ret = {};

    ret[innerElement[0]] = innerElement[1];
    return ret;
})

JsFiddle to test. JsFiddle进行测试。

With underscore: 带下划线:

var newArr = _.map(arrayTemp, function(item){
    for (var i in item){
       var o = {};
       o[item[i][0]] = item[i][1];
       return o;
    }
});

Although @François_Wahl's solution is the better one in my esteem using the native Array.prototype.map(). 尽管@François_Wahl的解决方案使用本机Array.prototype.map()在我看来是更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM