前端js算法面试题,前端基础面试题,lodash.keyBy函数实现

人气:262 ℃/2024-04-02 04:14:27

keyBy函数用法示例:

var array = [ { 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }]; _.keyBy(array, Function(o) { return String.fromCharCode(o.code);});// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } _.keyBy(array, 'dir');// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }

参数说明:

  1. collection (Array|Object): 待遍历的集合(数组或者对象)
  2. [iteratee=_.identity] (Function):用来转换key的遍历函数。

具体实现代码和测试代码:

// Lodashconsole.log(_.keyBy(['a', 'b', 'c']))// output: { a: 'a', b: 'b', c: 'c' }console.log(_.keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id'))// output: { a1: { id: 'a1', title: 'abc' }, b2: { id: 'b2', title: 'def' } }console.log(_.keyBy({ data: { id: 'a1', title: 'abc' }}, 'id'))// output: { a1: { id: 'a1', title: 'abc' }}// keyBy for array onlyconst keyBy = (array, key) => (array || []).reduce((r, x) => ({ ...r, [key ? x[key] : x]: x }), {});// Nativeconsole.log(keyBy(['a', 'b', 'c']))// output: { a: 'a', b: 'b', c: 'c' }console.log(keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id'))// output: { a1: { id: 'a1', title: 'abc' }, b2: { id: 'b2', title: 'def' } }console.log(keyBy(Object.values({ data: { id: 'a1', title: 'abc' }}), 'id'))// output: { a1: { id: 'a1', title: 'abc' }}// keyBy for array and objectconst collectionKeyBy = (collection, key) => { const c = collection || {}; return c.isArray() ? keyBy(c, key) : keyBy(Object.values(c), key);}

百科

More+
首页/电脑版/网名
© 2025 NiBaKu.Com All Rights Reserved.