+ 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.

14th Apr 2019, 6:21 AM
Ragey
Ragey - avatar
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));
14th Apr 2019, 7:50 AM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
+ 1
Thanks it worked! :)
14th Apr 2019, 7:54 AM
Ragey
Ragey - avatar