将数组转换为对象

将数组转换为对象你可以使用累加器aka reduce 。['a','b','c'].reduce(function(result,item,index,array){result[index]=item;//a,b,cret

大家好,欢迎来到IT知识分享网。将数组转换为对象"

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

 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/30431.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信