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?
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?
Share Improve this question edited Nov 1, 2016 at 13:49 user663031 asked Oct 31, 2016 at 7:08 soysoy 1431 silver badge9 bronze badges 1- Please let me know if there are any modules that can solve this problem simply. (similar to underscore.js) – soy Commented Oct 31, 2016 at 8:14
7 Answers
Reset to default 5Interesting 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);
Underscore solution:
output = _.object(..._.partition(input, (_, i) => !(i % 2)))
_.partition
will partition the array into [['name', 'age'], ["tom", "20"]]
. In other words, it returns an array containing two subarrays--in this case, one array of keys and one array of values. _.object
takes an array of keys and an array of values as parameters, so we use ...
to pass the subarrays in the value returned by _.partition
to it as two parameters.
If you're into very functional, semantic code:
const even = i => !(i % 2);
const index = fn => (_, i) => fn(i);
output = _.object(..._.partition(input, index(even)))
Recursive solution:
function arrayToObject([prop, value, ...rest], result = {}) {
return prop ? arrayToObject(rest, Object.assign(result, {[prop]: value})) : result;
}
Iterative solution:
function arrayToObject(arr) {
const result = {};
while (arr.length) result[arr.shift()] = arr.shift();
return result;
}
You may also use reduce
var arr = ["name", "Tom", "age", 20],
obj = arr.reduce((p,c,i,a) => (i%2 ? p[a[i-1]] = c : p[c],p),{});
console.log(obj);
for this operation as follows;
var input = ["name", "Tom", "age", 20] ;
var output = {}
input.forEach((x, i, arr) => {
if (i % 2 === 0) output[x] = arr[i+1];
});
console.log(output); //{ name: 'Tom', age: 20 }
A simple for loop
var arr = ["name", "Tom", "age", 20, "address"];
var obj = {};
for (var i = 0; i < arr.length; i+=2){
//First iteration: assign obj["name"] to "Tom"
//Second iteration: assign obj["age"] to 20
//Third iteration: assign obj["address"] to "" because arr[5] does not exist
obj[arr[i]] = arr[i+1] || "";
}
const arr = ["name", "Tom", "age", 20, "address", "London"];
function parseParams([k, v, ...rest]) {
return k ? { [k]: v, ...parseParams(rest) } : {};
}
console.log(JSON.stringify(parseParams(arr), null, 3));
// e.g. node js to get arguments that way
// parseParams(process.argv.slice(2));