+ 1
Is there a way write a function to turn arrays into objects in JavaScript?
If I have the array like ["key1", 10, "key2", 25]. How do I turn it into an object as {key1: 10, key2: 25} if it's possible, and I want a pretty simple approach which does not require too many lines of code.
2 Answers
+ 6
You could do something like this:
arr=["key1", 10, "key2", 25]
var obj = new Object();
for(var i=0;i<=arr.length/2;i +=2) {
obj[arr[i]]=arr[i+1];
}
// print object
console.log(JSON.stringify(obj));
+ 1
Thanks it worked! :)