如何在使用 map() 時只更改少數 Property ?

栏目: JavaScript · 发布时间: 7年前

内容简介:使用ECMAScript 2015我們希望對

使用 map() 的目的就在於修改原來 Array 的 Object,實務上可能只有幾個 Property 需要修改,其他的 Property 都必須保留;若原本 Property 不多,重複輸入 Property 問題不大,但若 Property 很多,這會是一個很大的負擔。

Version

ECMAScript 2015

基本寫法

const data = [
  { id: 1, name: 'Sam', city: 'Taipei' },
  { id: 2, name: 'Kevin', city: 'Tokyo' },
  { id: 3, name: 'Mike', city: 'Chicago'},
];

const mapping = x => ({
  id: x.id,
  city: x.city,
  name: `Mr. ${x.name}`
});

const result = data.map(mapping);
console.log(result);

我們希望對 name property 加工加上 Mr. ,其他 property 都必須保留。

最基本的寫法就是將原本的 property 都照抄一遍。

如何在使用 map() 時只更改少數 Property ?

Object.assign()

const data = [
  { id: 1, name: 'Sam', city: 'Taipei' },
  { id: 2, name: 'Kevin', city: 'Tokyo' },
  { id: 3, name: 'Mike', city: 'Chicago'},
];

const mapping = x => {
  const obj = Object.assign({}, x);
  obj.name = `Mr. ${x.name}`;
  return obj;
};

const result = data.map(mapping);
console.log(result);

使用 ECMAScript 2015 的 Object.assign() 複製一份新的 object,修改 property 之後,再 return 傳回。

如何在使用 map() 時只更改少數 Property ?

Object Spread

const data = [
  { id: 1, name: 'Sam', city: 'Taipei' },
  { id: 2, name: 'Kevin', city: 'Tokyo' },
  { id: 3, name: 'Mike', city: 'Chicago'},
];

const mapping = x => ({
  ...x,
  name: `Mr. ${x.name}`
});

const result = data.map(mapping);
console.log(result);

使用 ECMAScript 2015 的 Object Spread 將 x object 展開,再加上 name property,將會蓋掉原本的 name property。

如何在使用 map() 時只更改少數 Property ?

Conclusion

  • Object Spread 無疑是最漂亮的寫法,既直覺又優雅

Reference

MDN , Object.assign

MDN , Spread syntax


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Spring Boot实战

Spring Boot实战

[美]克雷格·沃斯 / 丁雪丰 / 人民邮电出版社 / 2016-9 / 59.00元

本书以Spring应用程序开发为中心,全面讲解如何运用Spring Boot提高效率,使应用程序的开发和管理更加轻松有趣。作者行文亲切流畅,以大量示例讲解了Spring Boot在各类情境中的应用,内容涵盖起步依赖、Spring Boot CLI、Groovy、Grails、Actuator。对于Spring Boot开发应用中较为繁琐的内容,附录奉上整理完毕的表格,一目了然,方便读者查阅。一起来看看 《Spring Boot实战》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码