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?
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With