ES6 換種思路處理數據

Handle javascript data structures with map/reduce

看完本文,但願能夠寫出更加漂亮、簡潔、函數式的代碼?javascript

reduce

reduce 能夠用來彙總數據java

const customer = [
  {id: 1, count: 2},
  {id: 2, count: 89},
  {id: 3, count: 1}
];
const totalCount = customer.reduce((total, item) =>
  total + item.count,
  0 // total 的初始值
);
// now totalCount = 92

把一個對象數組變成一個以數組中各個對象的 id 爲屬性名,對象自己爲屬性值的對象。haoduoshipines6

let products = [
  {
    id: '123',
    name: '蘋果'
  },
  {
    id: '345',
    name: '橘子'
  }
];

const productsById = products.reduce(
  (obj, product) => {
    obj[product.id] = product
    return obj
  },
  {}
);

console.log('result', productsById);

map

map 能夠理解爲是數組的轉換器,依次對數組中的每一個元素作變換進而獲得一個新的數組。編程

const integers = [1, 2, 3, 4, 6, 7];
const twoXIntegers = integers.map(i => i*2);
// twoXIntegers are now [2, 4, 6, 8, 12, 14]
// integers數組並不會受到影響

find?

篩選出數組中的個別元素小程序

const posts = [
  {id: 1, title: 'Title 1'},
  {id: 2, title: 'Title 2'},
];
// find the title of post whose id is 1
const title = posts.find(p => p.id === 1).title;

唉~ 使用了半年的 es6才發現有這麼好用的東西,譯者傻缺還像下面這麼寫過呢segmentfault

const posts = [
  {id: 1, title: 'Title 1'},
  {id: 2, title: 'Title 2'},
];

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

filter

篩選出數組中某些符合條件的元素組成新的數組數組

const integers = [1, 2, 3, 4, 6, 7];
const evenIntegers = integers.filter(i => i % 2 === 0);
// evenIntegers are [2, 4, 6]

請你們自行思考下filterfind的區別瀏覽器

數組concat

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 0];
const arrTarget = [...arr1, ...arr2];
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

對象操做

function operation(query, option = {}) {
    const param = {...query, ...option};
    // ....
    return param;
}
let opt = {startTime: 123455555, endTime: 113345555};
let q = {name: '一步', age: 'xxx'};
operation(q, opt);
// {name: "一步", age: "xxx", startTime: 123455555, endTime: 113345555}

對象是引用傳參的,因此函數內部應該儘量的保證傳入的參數不受到污染。編程語言

爲對象動態地添加字段

const dynamicKey = 'wearsSpectacles';
const user = {name: 'Shivek Khurana'};
const updatedUser = {...user, [dynamicKey]: true};
// updatedUser is {name: 'Shivek Khurana', wearsSpectacles: true}

將對象轉換爲query字符串?

const params = {color: 'red', minPrice: 8000, maxPrice: 10000};
const query = '?' + Object.keys(params)
  .map(k =>
    encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
  )
  .join('&')
;
// encodeURIComponent encodes special characters like spaces, hashes
// query is now "color=red&minPrice=8000&maxPrice=10000"

獲得對象數組的元素 index

const posts = [
  {id: 13, title: 'Title 221'},
  {id: 5, title: 'Title 102'},
  {id: 131, title: 'Title 18'},
  {id: 55, title: 'Title 234'}
];
// to find index of element with id 131
const requiredIndex = posts.map(p => p.id).indexOf(131);

更加優雅的寫法呱呱呱提供ide

const posts = [
  {id: 13, title: 'Title 221'},
  {id: 5, title: 'Title 102'},
  {id: 131, title: 'Title 18'},
  {id: 55, title: 'Title 234'}
];
const index = posts.findIndex(p => p.id === 131)

刪除對象的某個字段

const user = { name: 'Shivek Khurana', age: 23, password: 'SantaCl@use' };
const userWithoutPassword = Object.keys(user)
    .filter(key => key !== 'password')
    .map(key => ({[key]: user[key]}))
    .reduce((accumulator, current) => ({ ...accumulator, ...current }), {});

這裏我認爲原做者有點爲了函數式編程而函數式了,下面是個人解決方案:

const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const newUser = {...user};
delete newUser.password;
// {name: "Shivek Khurana", age: 23}

更現代的寫法YiHzo提供: ?????

const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
// 利用對象的解構,取出非password的全部字段
const {password, ...newUser} = user

以上代碼片斷的共同原則:不改變原數據。但願你們的代碼均可以儘量的簡潔,可維護?。

【開發環境推薦】 Cloud Studio 是基於瀏覽器的集成式開發環境,支持絕大部分編程語言,包括 HTML五、PHP、Python、Java、Ruby、C/C++、.NET 小程序等等,無需下載安裝程序,一鍵切換開發環境。 Cloud Studio提供了完整的 Linux 環境,而且支持自定義域名指向,動態計算資源調整,能夠完成各類應用的開發編譯與部署。
相關文章
相關標籤/搜索