ES6 换种思路处理数据

(点击上方公众号,可快速关注)

英文:Shivek Khurana  译文:一歩

https://segmentfault.com/a/1190000013099221


看完本文,希望可以写出更加漂亮、简洁、函数式的代码

reduce

reduce 可以用来 汇总数据。

  
  
  1. const customer = [

  2.  {id: 1, count: 2},

  3.  {id: 2, count: 89},

  4.  {id: 3, count: 1}

  5. ];

  6. const totalCount = customer.reduce((total, item) =>

  7.  total + item.count,

  8.  0 // total 的初始值

  9. );

  10. // now totalCount = 92

把一个对象数组变成一个以数组中各个对象的 id 为属性名,对象本身为属性值的对象。haoduoshipin(http://haoduoshipin.com/videos/240/)

  
  
  1. let products = [

  2.  {

  3.    id: '123',

  4.    name: '苹果'

  5.  },

  6.  {

  7.    id: '345',

  8.    name: '橘子'

  9.  }

  10. ];

  11. const productsById = products.reduce(

  12.  (obj, product) => {

  13.    obj[product.id] = product

  14.    return obj

  15.  },

  16.  {}

  17. );

  18. console.log('result', productsById);

map

map 可以理解为是数组的转换器,依次对数组中的每个元素做变换进而得到一个新的数组。

  
  
  1. const integers = [1, 2, 3, 4, 6, 7];

  2. const twoXIntegers = integers.map(i => i*2);

  3. // twoXIntegers are now [2, 4, 6, 8, 12, 14]

  4. // integers数组并不会受到影响

find?

筛选出数组中的 个别元素。

  
  
  1. const posts = [

  2.  {id: 1, title: 'Title 1'},

  3.  {id: 2, title: 'Title 2'},

  4. ];

  5. // find the title of post whose id is 1

  6. const title = posts.find(p => p.id === 1).title;

唉~ 使用了半年的 es6才发现有这么好用的东西,译者傻缺还像下面这么写过呢。

  
  
  1. const posts = [

  2.  {id: 1, title: 'Title 1'},

  3.  {id: 2, title: 'Title 2'},

  4. ];

  5. const title = posts.filter(item => item.id === 1)[0].title;

filter

筛选出数组中 某些符合条件的元素组成新的数组。

  
  
  1. const integers = [1, 2, 3, 4, 6, 7];

  2. const evenIntegers = integers.filter(i => i/2 === 0);

  3. // evenIntegers are [2, 4, 6]

请大家自行思考下 filterfind的区别

数组concat
  
  
  1. const arr1 = [1, 2, 3, 4, 5];

  2. const arr2 = [6, 7, 8, 9, 0];

  3. const arrTarget = [...arr1, ...arr2];

  4. // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

对象操作
  
  
  1. function operation(query, option = {}) {

  2.    const param = {...query, ...option};

  3.    // ....

  4.    return param;

  5. }

  6. let opt = {startTime: 123455555, endTime: 113345555};

  7. let q = {name: '一步', age: 'xxx'};

  8. operation(q, opt);

  9. // {name: "一步", age: "xxx", startTime: 123455555, endTime: 113345555}

对象是引用传参的,所以函数内部应该尽可能的保证传入的参数不受到污染。

为对象动态地添加字段
  
  
  1. const dynamicKey = 'wearsSpectacles';

  2. const user = {name: 'Shivek Khurana'};

  3. const updatedUser = {...user, [dynamicKey]: true};

  4. // updatedUser is {name: 'Shivek Khurana', wearsSpectacles: true}

将对象转换为query字符串?
  
  
  1. const params = {color: 'red', minPrice: 8000, maxPrice: 10000};

  2. const query = '?' + Object.keys(params)

  3.  .map(k =>

  4.    encodeURIComponent(k) + '=' + encodeURIComponent(params[k])

  5.  )

  6.  .join('&')

  7. ;

  8. // encodeURIComponent encodes special characters like spaces, hashes

  9. // query is now "color=red&minPrice=8000&maxPrice=10000"

得到对象数组的元素 index
  
  
  1. const posts = [

  2.  {id: 13, title: 'Title 221'},

  3.  {id: 5, title: 'Title 102'},

  4.  {id: 131, title: 'Title 18'},

  5.  {id: 55, title: 'Title 234'}

  6. ];

  7. // to find index of element with id 131

  8. const requiredIndex = posts.map(p => p.id).indexOf(131);

更加优雅的写法呱呱呱提供:

  
  
  1. const posts = [

  2.  {id: 13, title: 'Title 221'},

  3.  {id: 5, title: 'Title 102'},

  4.  {id: 131, title: 'Title 18'},

  5.  {id: 55, title: 'Title 234'}

  6. ];

  7. const index = posts.findIndex(p => p.id === 131)

删除对象的某个字段
  
  
  1. const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};

  2. const userWithoutPassword = Object.keys(user)

  3.  .filter(key => key !== 'password')

  4.  .map(key => {[key]: user[key]})

  5.  .reducer((accumulator, current) =>

  6.    ({...accumulator, ...current}),

  7.    {}

  8.  )

  9. ;

  10. // userWithoutPassword becomes {name: 'Shivek Khurana', age: 23}

这里我认为原作者有点为了函数式编程而函数式了,下面是我的解决方案:

  
  
  1. const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};

  2. const newUser = {...user};

  3. delete newUser.password;

  4. // {name: "Shivek Khurana", age: 23}

以上代码片段的共同原则:不改变原数据。希望大家的代码都可以尽可能的简洁,可维护?。


觉得本文对你有帮助?请分享给更多人

关注「前端大全」,提升前端技能

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值