📜  lodash pickkby - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:26.318000             🧑  作者: Mango

Lodash PickBy - JavaScript

Lodash PickBy is a utility function in the Lodash library that creates a new object by picking the properties of an existing object that satisfy a given predicate function. The properties are picked based on the value returned by calling the predicate function on each property.

Installation

To use Lodash PickBy, you have to install the Lodash library. You can do this using npm:

npm install --save lodash
Syntax
_.pickBy(object, [predicate=_.identity])

The _.pickBy() function takes two arguments:

  • object (Object): The object to iterate over.
  • [predicate=_.identity] (Function): The function invoked per property. Returns true to pick the property, else false.
Example
const _ = require('lodash');

const person = {
  name: 'John',
  age: 28,
  city: 'New York',
  isAdmin: false,
  isUser: true
};

const user = _.pickBy(person, (value, key) => {
  return key.startsWith('is');
});

console.log(user);
// Output: { isAdmin: false, isUser: true }

In the above example, the _.pickBy() function picks the properties "isAdmin" and "isUser" from the person object because they satisfy the predicate function, which checks if the property key starts with "is". The picked properties are then used to create a new object user using the property values from the original person object.

Conclusion

Lodash PickBy is a powerful utility function that allows you to pick properties from an object based on a given predicate function. It is part of the popular Lodash library that provides a wide range of utility functions for JavaScript programming.