Home >Web Front-end >JS Tutorial >Lodash - a javascript power tool
Lodash, a lightweight replacement for Underscore.js, is a popular JavaScript utility library that simplifies common programming tasks. Explore the top 20 Lodash functions below to enhance your JavaScript skills:
const obj = { a: { b: { c: 42 } } }; _.get(obj, 'a.b.c', 'default'); // 42
const obj = {}; _.set(obj, 'a.b.c', 42); console.log(obj); // { a: { b: { c: 42 } } }
const arr = [{ a: 1 }]; const deepClone = _.cloneDeep(arr);
const log = _.debounce(() => console.log('Debounced!'), 300); window.addEventListener('resize', log);
const log = _.throttle(() => console.log('Throttled!'), 1000); window.addEventListener('scroll', log);
_.isEmpty([]); // true _.isEmpty({}); // true _.isEmpty(''); // true
const obj1 = { a: { b: 1 } }; const obj2 = { a: { c: 2 } }; _.merge(obj1, obj2); // { a: { b: 1, c: 2 } }
const obj = { a: 1, b: 2, c: 3 }; _.pick(obj, ['a', 'c']); // { a: 1, c: 3 }
const obj = { a: 1, b: 2, c: 3 }; _.omit(obj, ['b']); // { a: 1, c: 3 }
_.uniq([1, 2, 2, 3]); // [1, 2, 3]
_.groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] }
const users = [{ name: 'Tom', age: 30 }, { name: 'Jerry', age: 20 }]; _.sortBy(users, 'age'); // [{ name: 'Jerry', age: 20 }, { name: 'Tom', age: 30 }]
_.map([1, 2, 3], n => n * 2); // [2, 4, 6]
_.filter([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]
_.find([1, 2, 3, 4], n => n > 2); // 3
_.flatten([1, [2, [3, [4]]]]); // [1, 2, [3, [4]]]
_.flattenDeep([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
const obj = { a: { b: { c: 42 } } }; _.get(obj, 'a.b.c', 'default'); // 42
const obj = {}; _.set(obj, 'a.b.c', 42); console.log(obj); // { a: { b: { c: 42 } } }
const arr = [{ a: 1 }]; const deepClone = _.cloneDeep(arr);
Keep learning and having FUN !
The above is the detailed content of Lodash - a javascript power tool. For more information, please follow other related articles on the PHP Chinese website!