欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将数组转换为对象

程序员文章站 2022-04-29 10:57:27
...

本文翻译自:Convert Array to Object

What is the best way to convert: 转换的最佳方式是什么:

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

to: 至:

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

#1楼

参考:https://stackoom.com/question/Hghl/将数组转换为对象


#2楼

Quick and dirty #2: 快速而肮脏的#2:

var i = 0
  , s = {}
  , a = ['A', 'B', 'C'];

while( a[i] ) { s[i] = a[i++] };

#3楼

Here's a solution in coffeescript 这是coffeescript的解决方案

arrayToObj = (arr) ->
  obj = {}
  for v,i in arr
    obj[i] = v if v?
  obj

#4楼

This allows you to generate from an array an object with keys you define in the order you want them. 这允许您从数组生成一个对象,该对象具有您按照所需顺序定义的键。

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); will output "paint", the function has to have arrays of equal length or you get an empty object. 将输出“paint”,该函数必须具有相等长度的数组,否则您将得到一个空对象。

Here is an updated method 这是一个更新的方法

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

#5楼

You could use an accumulator aka reduce . 你可以使用累加器aka reduce

['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"

Pass an empty object {} as a starting point; 传递空对象{}作为起点; then "augment" that object incrementally. 然后逐渐“增加”该对象。 At the end of the iterations, result will be {"0": "a", "1": "b", "2": "c"} 在迭代结束时, result将为{"0": "a", "1": "b", "2": "c"}

If your array is a set of key-value pair objects: 如果您的数组是一组键值对对象:

[{ 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;
}, {});

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

For the sake of completeness, reduceRight allows you to iterate over your array in reverse order: 为了完整起见, reduceRight允许您以相反的顺序迭代数组:

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

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

Your accumulator can be of any type for you specific purpose. 您的累加器可以是任何类型的特定用途。 For example in order to swap the key and value of your object in an array, pass [] : 例如,为了在数组中交换对象的键和值,传递[]

[{ 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

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

Unlike map , reduce may not be used as a 1-1 mapping. map不同, reduce不能用作1-1映射。 You have full control over the items you want to include or exclude. 您可以完全控制要包含或排除的项目。 Therefore reduce allows you to achieve what filter does, which makes reduce very versatile: 因此, reduce可以让你实现filter功能,这使得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

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

Caution : reduce and Object.key are part of ECMA 5th edition ; 注意reduceObject.keyECMA 5th edition一部分; you should provide a polyfill for browsers that don't support them (notably IE8). 你应该为不支持它们的浏览器提供polyfill(特别是IE8)。

See a default implementation by Mozilla . 请参阅Mozilla的默认实现。


#6楼

Here's a recursive function I just wrote. 这是我刚写的一个递归函数。 It's simple and works well. 这很简单,效果很好。

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

Here's an example ( jsFiddle ): 这是一个例子( jsFiddle ):

var array = new Array();
array.a = 123;
array.b = 234;
array.c = 345;
var array2 = new Array();
array2.a = 321;
array2.b = 432;
array2.c = 543;
var array3 = new Array();
array3.a = 132;
array3.b = 243;
array3.c = 354;
var array4 = new Array();
array4.a = 312;
array4.b = 423;
array4.c = 534;
var array5 = new Array();
array5.a = 112;
array5.b = 223;
array5.c = 334;

array.d = array2;
array4.d = array5;
array3.d = array4;
array.e = array3;


console.log(array);

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}
console.log(convArrToObj(array));

Results: 结果: 将数组转换为对象