I am a bit stuck in finding a simple and elegant way to convert an Array like
const array = ["k1", "v1", "k2", "v2"]
to an object
const obj = {"k1": "v1", "k2": "v2"}
Just looking for inspirations
I am a bit stuck in finding a simple and elegant way to convert an Array like
const array = ["k1", "v1", "k2", "v2"]
to an object
const obj = {"k1": "v1", "k2": "v2"}
Just looking for inspirations
Maybe the good-old for-loop ?
To recap the proposed solutions
const obj = {}
for (let i = 0; i < array.length; i += 2) {
obj[array[i]] = array[i + 1]
}
const obj = array.reduce((acc, curval, idx, arr) => (idx % 2) == 0 ?
(acc[curval] = arr[idx+1], acc) : acc, {});
I like this solution the most, but it has lodash as dependency.
Would be cool if ES could implement it natively array.chunk(2)
Object.fromEntries(_.chunk(array))
A bit long to really be called a one-liner but if you can find a nice way to chunk the array into pairs then you can just give that to Object.fromEntries. Something like lodash's _.chunk would make this look a lot better but barring that:
const array = ["k1", "v1", "k2", "v2"]
const obj = Object.fromEntries(Array.from({length: array.length / 2}, (_, i) => array.slice(i, i+2)))
console.log(obj);
With Array.reduce():
const array = ["k1", "v1", "k2", "v2"];
var newarr = array.reduce((acc, curval, idx, arr) => (idx % 2) == 0 ?
(acc[curval] = arr[idx+1], acc) : acc, {});
console.log(newarr);
You can accomplish this with the code below:
const array = ["k1", "v1", "k2", "v2"];
let obj = {};
for (let i = 0; i < array.length; i+=2) {
obj[array[i]] = array[i+1];
}
console.log("Array: "+array);
console.log("\nObject: "+array);
console.log(" k1: "+obj["k1"]);
console.log(" k2: "+obj.k2);
Not so elegant, but might lead for farther thoughts:
Using map, reduce, and lodash merging:
let array = ["a1", "b1", "a2", "b2"];
array = array.map((e,i)=>{
let newobj={};
newobj[e]=array[i+1];
return i%2===0?newobj:{}
});
array.reduce((v1,v2)=>_.merge(v1, v2));
(Assuming an even number of elements in array)
Using a function like chunk, but with pure Js:
const array = ["k1", "v1", "k2", "v2"]
function chunks(arr, size = 2) {
return arr.map((x, i) => i % size == 0 && arr.slice(i, i + size)).filter(x => x)
}
console.log(Object.fromEntries(chunks(array)))
And this one is using flatMap():
const array2 = ["k1", "v1", "k2", "v2"]
const pairs = (arr)=>{return arr.flatMap((_, i, a) => i % 2 ? [] : [a.slice(i, i + 2)])}
console.log(Object.fromEntries(pairs(array2)))