最好的转换方式是什么:

['a','b','c']

to:

{
  0: 'a',
  1: 'b',
  2: 'c'
}

当前回答

我的版本数组json在JS。只需要复制/粘贴并使用它。这是不是很棒?我喜欢我在StackOverflow上发现的这类函数。

function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
        var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");

    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}

其他回答

ECMAScript 6引入了易于多填充的Object.assign:

Object.assign()方法用于复制所有对象的值 可枚举对象拥有的属性,从一个或多个源对象到目标 对象。它将返回目标对象。

Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}

数组本身的length属性不会被复制,因为它是不可枚举的。

此外,你可以在对象上使用ES8扩展语法来实现相同的结果:

{ ...['a', 'b', 'c'] }

对于自定义键,您可以使用reduce:

['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {}) 
// { a: "a", b: "b", c: "c" }

你可以使用累加器,也就是减少。

['a','b','c'].reduce(function(result, item, index, array) {
  result[index] = item; //a, b, c
  return result;
}, {}) //watch out the empty {}, which is passed as "result"

传递一个空对象{}作为起始点;然后递增地“增大”该对象。 在迭代结束时,结果将是{"0":"a", "1": "b", "2": "c"}

如果数组是键值对对象的集合:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {
  var key = Object.keys(item)[0]; //first property: a, b, c
  result[key] = item[key];
  return result;
}, {});

将产生:{a: 1, b: 2, c: 3}

为了完整起见,reduceRight允许你以相反的顺序遍历数组:

[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)

将产生:{c:3, b:2, a:1}

你的蓄能器可以为你的特定用途的任何类型。例如,为了交换数组中对象的键和值,传递[]:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
  var key = Object.keys(item)[0]; //first property: a, b, c
  var value = item[key];
  var obj = {};
  obj[value] = key;
  result.push(obj);
  return result;
}, []); //an empty array

将产生:[{1:"a"}, {2: "b"}, {3: "c"}]

与map不同,reduce不能用作1-1映射。您可以完全控制要包含或排除的项。因此,reduce可以实现过滤器的功能,这使得reduce非常通用:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {
  if(index !== 0) { //skip the first item
    result.push(item);
  }
  return result;
}, []); //an empty array

将产生:[{2:"b"}, {3: "c"}]

警告:减少和对象。关键是ECMA第5版的一部分;你应该为不支持它们的浏览器(尤其是IE8)提供一个polyfill。

请参阅Mozilla的默认实现。

一个简单和厚脸皮的方法,快速转换数组的项目到一个对象

function arrayToObject( srcArray ){
    return  JSON.parse( JSON.stringify( srcArray ) );
}

然后像这样使用它…

var p = [0,2,3,'pork','pie',6];
obj = new arrayToObject( p );
console.log( obj[3], obj[4] )
// expecting `pork pie`

输出:

pork pie

检查类型:

typeof obj
"object"

如果没有原型方法,事情就不完整

Array.prototype.toObject =function(){
    return  JSON.parse( JSON.stringify( this ) );
}

使用:

var q = [0,2,3,'cheese','whizz',6];
obj = q.toObject();
console.log( obj[3], obj[4] )
// expecting `cheese whizz`

输出:

cheese whizz

*注意,没有命名例程,所以如果你想要特定的名称,那么你将需要继续使用下面现有的方法。


老的方法

这允许您从一个数组生成一个对象,其中的键是按照您想要的顺序定义的。

Array.prototype.toObject = function(keys){
    var obj = {};
    var tmp = this; // we want the original array intact.
    if(keys.length == this.length){
        var c = this.length-1;
        while( c>=0 ){
            obj[ keys[ c ] ] = tmp[c];
            c--;
        }
    }
    return obj;
};

result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);

Console.log (">>>:" + result.onion);将输出"paint",函数必须有相等长度的数组,否则将得到一个空对象。

这里是一个更新的方法

Array.prototype.toObject = function(keys){
    var obj = {};
    if( keys.length == this.length)
        while( keys.length )
            obj[ keys.pop() ] = this[ keys.length ];
    return obj;
};

这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行

const nodes = {
    node1: {
        interfaces: {if1: {}, if2: {}}
    },
    node2: {
        interfaces: {if3: {}, if4: {}}
    },
    node3: {
        interfaces: {if5: {}, if6: {}}
    },
}

解决方案是结合使用reduce和对象扩展:

const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})

最短的答案:(使用解构)

const obj = { ...input }

例子:

const inputArray = ["a", "b", "c"]
const outputObj = { ...inputArray }