简体   繁体   中英

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.

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.

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


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.

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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