How to use the pluck function from underscore

Find comprehensive JavaScript underscore.pluck code examples handpicked from public code repositorys.

underscore.pluck is a function that extracts a list of property values from a collection of objects.

104
105
106
107
108
109
110
111
112
113
 * @param {Array} newArray              List of attributes of the configuration.
 * @return {Array}                      Merge of the attributes of the device and those of the configuration.
 */
function mergeArrays(original, newArray) {
    /* jshint camelcase: false */
    const originalKeys = _.pluck(original, 'object_id');
    const newKeys = _.pluck(newArray, 'object_id');
    const addedKeys = _.difference(newKeys, originalKeys);
    const differenceArray = newArray.filter(function (item) {
        return item.object_id && addedKeys.indexOf(item.object_id) >= 0;
fork icon74
star icon56
watch icon23

+ 3 other calls in file

3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
const currentAttributes = JSON.parse(
    vcdEntry.attributes
);
let renderedSignals = currentAttributes.rendered || [];
let hiddentSignals = currentAttributes.hidden || [];
const allSignals = _.pluck(wave.signal, "name");
const newSignals = _.difference(
    allSignals,
    renderedSignals.concat(hiddentSignals)
);
fork icon0
star icon2
watch icon3

+ 5 other calls in file

How does underscore.pluck work?

underscore.pluck takes two arguments: a collection (usually an array of objects) and a string representing the name of a property.

The function then returns an array of values that correspond to that property in each of the objects in the collection.

For example, if we had an array of objects representing books with properties such as title, author, and yearPublished, we could use underscore.pluck to extract an array of all of the book titles:

javascript
const books = [ { title: "The Great Gatsby", author: "F. Scott Fitzgerald", yearPublished: 1925 }, { title: "To Kill a Mockingbird", author: "Harper Lee", yearPublished: 1960 }, { title: "Pride and Prejudice", author: "Jane Austen", yearPublished: 1813 } ]; const titles = _.pluck(books, 'title'); console.log(titles); // ["The Great Gatsby", "To Kill a Mockingbird", "Pride and Prejudice"]

In this example, we pass the books array as the first argument to _.pluck, and the string 'title' as the second argument. The function then returns an array containing the values of the title property for each book in the array.

2336
2337
2338
2339
2340
2341
2342
2343
2344
// an index go together.
_.zip = function() {
  var length = _.max(_.pluck(arguments, "length").concat(0));
  var results = new Array(length);
  for (var i = 0; i < length; i++) {
    results[i] = _.pluck(arguments, '' + i);
  }
  return results;
};
fork icon0
star icon2
watch icon0

+ 3 other calls in file

197
198
199
200
201
202
203
204
205
206
var _validateRecord = function(schema, obj) {
  if (!_.isObject(obj) || _.isArray(obj)) {
    throw new ValidationError('Expected record Javascript type to be non-array object, got ' + JSON.stringify(obj));
  }

  var schemaFieldNames = _.pluck(schema.fields, 'name').sort();
  var objFieldNames = _.keys(obj).sort();
  if (!_.isEqual(schemaFieldNames, objFieldNames)) {
    throw new ValidationError('Expected record fields ' + JSON.stringify(schemaFieldNames) + '; got ' + JSON.stringify(objFieldNames));
  }
fork icon0
star icon1
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
const users = [
  { id: 1, name: "Alice", age: 25 },
  { id: 2, name: "Bob", age: 30 },
  { id: 3, name: "Charlie", age: 35 },
];

const names = _.pluck(users, "name");

console.log(names); // ["Alice", "Bob", "Charlie"]

In this example, we have an array of user objects with properties such as id, name, and age. We use _.pluck to extract the name property from each object, and store the resulting array of names in the names variable. The function then returns an array containing the values of the name property for each user in the array.

852
853
854
855
856
857
858
859
860
861
// an index go together.
_.zip = function() {
  var args = slice.call(arguments);
  var length = _.max(_.pluck(args, 'length'));
  var results = new Array(length);
  for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
  return results;
};

// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
fork icon0
star icon0
watch icon1

+ 13 other calls in file

2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
let questionList = [];
let orgId = params.orgId;
customerService.getCategoryAssesmentDetail(params.categoryId,orgId)
.then(async function(data){
    let assesmentData = await customerService.getAssesmentSurvey(params.categoryId,orgId);
    let questionIds = _.pluck(data,'questionId');
    questionIds = _.uniq(questionIds);
    questionIds.forEach(questionId => {
        let questionData = {};
        let questionsArray = _.reject(data,(questionobj)=>{
fork icon0
star icon0
watch icon1

+ 24 other calls in file

32
33
34
35
36
37
38
39
40
41
if(authData.isKeyStaff)
{
    let totalCount = await notificationService.getOrgNotificationCount(authData.adminId)
    console.log(totalCount[0].count);

    // let ids = _.pluck(totalCount,'communication_id');
    // console.log(ids);
    // ids = ids.filter(function( element ) {
    //     return element !== undefined;
    //  });
fork icon0
star icon0
watch icon1

+ 5 other calls in file

8863
8864
8865
8866
8867
8868
8869
8870
8871
_.zip = function() {
  var args = slice.call(arguments);
  var length = _.max(_.pluck(args, 'length'));
  var results = new Array(length);
  for (var i = 0; i < length; i++) {
    results[i] = _.pluck(args, "" + i);
  }
  return results;
};
fork icon0
star icon0
watch icon1

+ 5 other calls in file

445
446
447
448
449
450
451
452
453
454
    filters: [
        ['_id', 'in', su.organizations]
    ],
    fields: ['company_id']
});
company_ids = _.pluck(orgs, 'company_id');
// company_ids中的空值就空着,不需要转换成根组织ID值
company_ids = _.uniq(_.compact(company_ids));
await suObj.directUpdate(_id, {
    company_ids: company_ids
fork icon0
star icon0
watch icon1

7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
bookingData[i].status = bookingData[i].currentStatus;
bookingData[i].currentStatus = configs.MessageConfiguration.get('/lang', {
  locale: lang,
  message: bookingData[i].currentStatus,
});
service = _.pluck(bookingData[i].services, 'serviceName');
service = service.join();
if (bookingData[i].status == bookingConfiguration.get('/BOOKING_STATUS', {
  STATUS: 'COMPLETED',
})) {
fork icon0
star icon0
watch icon1

+ 15 other calls in file

7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
  customerID: 1,
}, {
  lean: true,
},
'customerID');
customers = _.pluck(customers, 'customerID');
// if(customers.length > 0) {
// customers.map(async (c) => {
// if (c && c.deviceToken && c.deviceType) {
services.Notification.sendPUSHToUser(payloadData.token, payloadData.deviceType, null, messageData, notificationType);
fork icon0
star icon0
watch icon1

+ 7 other calls in file

87
88
89
90
91
92
93
94
95
96
axis: {
    // shows labels on left when there are more than 10 columns
    rotated: this.data.length > 10,
    x: {
        type: 'category',
        categories: _.pluck(this.data, 0)
    }
},
legend: { show: false },
transition: { duration: 0 }
fork icon0
star icon0
watch icon2

+ 2 other calls in file