Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to object, based on even/odd index

I am trying to convert an array to an object based on whether the index of array is odd or even.

For example,,

Input: ["name", "Tom", "age", 20]

output:{ "name": "tom","age": 20 }

It can be implemented using basic functions of JavaScript such as forEach, map, and filter. But I want more simple code.

So I checked docs of underscore.js, but I couldn't find a good way. Is there any way to solve this simply?

like image 686
soy Avatar asked Oct 31 '16 07:10

soy


2 Answers

Interesting question, my two cents:

Simple and performant for loop:

const simpleArray = ["name", "Tom", "age", 20];

// Modifying the Array object
Array.prototype.toObject = function() {
    let r = {};

    for(let i = 0; i < this.length; i += 2) {
        let key = this[i], value = this[i + 1];
        r[key] = value;
    }

    return r;
}

// Or as a function
const toObject = arr => {
    let r = {};

    for(let i = 0; i < arr.length; i += 2) {
        let key = arr[i], value = arr[i + 1];
        r[key] = value;
    }

    return r;
}

const simpleObjectOne = simpleArray.toObject(); // First method
const simpleObjectTwo = toObject(simpleArray); // Second method
like image 92
Aramil Rey Avatar answered Nov 08 '22 20:11

Aramil Rey


You could use Array#forEach and a check for the index, if uneven, then assign the element to the key from the last item.

var array =  ["name", "Tom", "age", 20],
    object = {};

array.forEach(function (a, i, aa) {
    if (i & 1) {
        object[aa[i - 1]] = a;
    }
});

console.log(object);

The same with Array#reduce

var array =  ["name", "Tom", "age", 20],
    object = array.reduce(function (r, a, i, aa) {
        if (i & 1) {
            r[aa[i - 1]] = a;
        }
        return r;
    }, {});

console.log(object);
like image 4
Nina Scholz Avatar answered Nov 08 '22 21:11

Nina Scholz