网站更新内容:请访问: https://bigdata.ministep.cn/

JavaScript:将对象数组映射到字典

JavaScript:将对象数组映射到字典

在 JavaScript / TypeScript 中将对象数组转换为字典的最简单方法:

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country})));
// {1: "Germany", 2: "Austria", 3:

 

另外一种办法:

Object.fromEntries很好,像这样使用怎么样:

let dictionary = Object.fromEntries(data.map(x => [x.id, x.country]));
 
posted @ 2023-07-16 14:26  ministep88  阅读(628)  评论(0)    收藏  举报
网站更新内容:请访问:https://bigdata.ministep.cn/