Gabriel
Gabriel

Reputation: 690

object to array preserve key as first element

i have this object that i need to transform to array and set the object key as the first element of the array, this is what i got so far:

var a = {0:['a','b'],1:['c','d']},out =[];
out = Object.keys(a).map(function (key) { a[key][a[key].length] = key; return a[key]});

but the key is the last element, out is [["a", "b", "0"], ["c", "d", "1"]]

and i need it to be [["0", "a", "b"], ["1", "c", "d"]]

after that i used this function to set the third array element to the first position:

Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
    var k = new_index - this.length;
    while ((k--) + 1) {
        this.push(undefined);
    }
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};

is there a better way to do this without rearranging the array elements? i don't use jquery or other libraries

here is a jsfiddle for testing: https://jsfiddle.net/9zv6cyau/

Thanks

Upvotes: 0

Views: 141

Answers (1)

Tushar
Tushar

Reputation: 87203

Use Array#unshift to add the element at the beginning of array

Demo

var a = {
        0: ['a', 'b'],
        1: ['c', 'd']
    },
    out = [];

out = Object.keys(a).map(function (key) {
    a[key].unshift(key); // Add the key at the beginning of array
    return a[key];
});
console.log(out);

document.body.innerHTML = '<pre>' + JSON.stringify(out, 0, 4) + '</pre>';

Upvotes: 1

Related Questions