Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

前端 未结 3 486
旧时难觅i
旧时难觅i 2020-12-11 05:37

Is there a simple way in javascript to take a flat array and convert into an object with the even-indexed members of the array as properties and odd-indexed members as corre

3条回答
  •  天涯浪人
    2020-12-11 06:26

    Pretty sure this will work and is shorter:

    var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
    var obj = {};
    while (arr.length) {
        obj[arr.shift()] = arr.shift();
    }
    

    See shift().

提交回复
热议问题