将数组转换为对象

你可以使用累加器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"

传递空对象{}作为起点; 然后逐渐“增加”该对象。 {"0": "a", "1": "b", "2": "c"} 在迭代结束时, 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;
}, {});

为了完整起见, reduceRight允许您以相反的顺序迭代数组:

[{ a: 1},{ b: 2},{ c: 3}]

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

[{ 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"}] 将产生: [{1: "a"}, {2: "b"}, {3: "c"}]

 

posted @ 2021-07-09 16:18  MrSlow  阅读(2251)  评论(0)    收藏  举报