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

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

内容简介:使用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


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

查看所有标签

猜你喜欢:

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

Web Data Mining

Web Data Mining

Bing Liu / Springer / 2006-12-28 / USD 59.95

Web mining aims to discover useful information and knowledge from the Web hyperlink structure, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is n......一起来看看 《Web Data Mining》 这本书的介绍吧!

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

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

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

多种字符组合密码