You-Dont-Need-Lodash-Underscore

● You-Dont-Need-Lodash-Underscore

https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

● lodash代替コード 検索サイト

https://youmightnotneed.com/lodash/

_.find の例

// Native JavaScript
var users = [
  { 'id': 1 , 'user': 'barney',  'age': 36, 'active': true },
  { 'id': 2 , 'user': 'fred',    'age': 40, 'active': false },
  { 'id': 3 , 'user': 'pebbles', 'age': 1,  'active': true }
]

const id = 3;
const user = users.find(function (o) { return o.id === id; })

_.pluck の例

// Underscore/Lodash
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = _.pluck(array1, "name")
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]

// Native
var array1 = [{name: "Alice"}, {name: "Bob"}, {name: "Jeremy"}]
var names = array1.map(function(x){
  return x.name
})
console.log(names)
// output: ["Alice", "Bob", "Jeremy"]

アロー関数でこのように記述できます

const names = array1.map(x => x.name);

_.uniq の例

// Underscore/Lodash
var array = [1, 2, 1, 4, 1, 3]
var result = _.uniq(array)
console.log(result)
// output: [1, 2, 4, 3]

// Native
var array = [1, 2, 1, 4, 1, 3];
var result = [...new Set(array)];
console.log(result)
// output: [1, 2, 4, 3]

複数の配列の共通する値を取得する _.intersection の例

// Underscore/Lodash
console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]))
// output: [1, 2]

// Native
var arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce(function(a, b) {
  return a.filter(function(value) {
    return b.includes(value);
  });
}));
// output: [1, 2]

// ES6
let arrays = [[1, 2, 3], [101, 2, 1, 10], [2, 1]];
console.log(arrays.reduce((a, b) => a.filter(c => b.includes(c))));
// output: [1, 2]

コレクション内に特定の キーの存在を確認する _.has

// Lodash
var object = { a: 1, b: 'settings', c: { d: 'test' } };
  
var hasA = _.has(object, 'a');
var hasCWhichHasD = _.has(object, 'c.d')

console.log(hasA);
// output: true
console.log(hasCWhichHasD);
// output: true

// Native
const has = function (obj, key) {
  var keyParts = key.split('.');

  return !!obj && (
    keyParts.length > 1
      ? has(obj[key.split('.')[0]], keyParts.slice(1).join('.'))
      : hasOwnProperty.call(obj, key)
  );
};

var object = { a: 1, b: 'settings' };
var result = has(object, 'a'); 
// output: true

参考 : https://bit.ly/3guGUik

No.1927
10/21 16:01

edit