Skip to content

Latest commit

 

History

History
21 lines (15 loc) · 655 Bytes

objectFromPairs.md

File metadata and controls

21 lines (15 loc) · 655 Bytes
标题 标签
objectFromPairs(从给定键值对创建对象) object,array(对象,数组)

从给定的键值对创建一个对象。

  • 使用 Array.prototype.reduce() 创建和组合键值对。
  • Object.fromEntries() 提供了类似的功能。
const objectFromPairs = arr => [...arr].reduce((res,[key,val]) => ((res[key] = val),res),{});

调用方式:

objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
objectFromPairs(new Map([['a', 1], ['b', 2]])); // {a: 1, b: 2}

应用场景