使用现代 API 映射 JavaScript 对象
Object.entries允许您将对象转换为数组结构:
console.log(Object.entries({prop1: 1, prop2: 2 }))
// [ ["prop1", 1], ["prop2", 2] ]
此方法是 ECMAScript 2017 规范的一部分,已被许多开发人员(包括我)大量使用。
直到最近,还没有方便的方法可以将这种结构转换回对象。
现在,我们终于有了Object.fromEntries可以从返回的结构构造一个对象的方法Object.entries。
这使得映射对象变得非常方便:
执行:
const mapValues = (input, mapper) =>
  Object.fromEntries(
    Object.entries(input).map(([key, value]) => [
      key,
      mapper(value, key, input)
    ])
  );
使用示例:
const input = {
  prop1: 1,
  prop2: 4,
};
const output = mapValues(input, value => value * 2);
expect(output).toEqual({
  prop1: 2,
  prop2: 8,
});
支持
浏览器支持:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility
 Node 支持:https://node.green/#ES2019-features--Object-fromEntries
 后端开发教程 - Java、Spring Boot 实战 - msg200.com
            后端开发教程 - Java、Spring Boot 实战 - msg200.com