How to use the keys function from underscore

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

underscore.keys is a function in the Underscore.js library that returns an array of all the keys in an object.

201
202
203
204
205
206
207
208
209
210
211
    retVal += file.replace('.md', '').replace(postsRoot, '').replace(postsRoot.replace('./', ''), '');
    return retVal;
}


function performMetadataReplacements(replacements, haystack) {
    _.keys(replacements).each(function (key) {
        // Ensure that it's a global replacement; non-regex treatment is first-only.
        haystack = haystack.replace(new RegExp(metadataMarker + key + metadataMarker, 'g'), replacements[key]);
    });

fork icon54
star icon266
watch icon27

+ 77 other calls in file

160
161
162
163
164
165
166
167
168
169
let entityType;

const attribute = req.params.attr;
const value = req.body.value;
const datasetId = req.body.datasetId;
const incomingAttrs = !req.params.attr ? _.keys(req.body) : [];

if (contextElement.id && contextElement.type) {
    entityId = contextElement.id;
    entityType = contextElement.type;
fork icon74
star icon56
watch icon23

How does underscore.keys work?

underscore.keys is a function that takes an object as input and returns an array of the object's own enumerable property names.

116
117
118
119
120
121
122
123
124
125
        provinceObject[`province ${index + 1}`] = { provinceCard: card };
    });
    newProvinceState = provinceObject;
}
//Move all province cards to province deck
var allProvinceLocations = _.keys(this.provinces);
_.each(this.provinces, (contents) => {
    this.moveCard(contents.provinceCard, 'province deck');
});
//Fill the specified provinces
fork icon18
star icon17
watch icon0

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
    return next( err );
}

var fields = r.getFields( req );

async.map( _.keys( renderCrud.foreignKeys ), function( fkey, done ) {

    if( !_.has( fields, fkey ) && ( opts.hiddenForeignKeys || [] ).indexOf( fkey ) < 0 )
    {
        console.log( "ForeignKey not registered: ".bold.yellow, fkey )
fork icon3
star icon9
watch icon1

+ 23 other calls in file

Ai Example

1
2
3
const object = { a: 1, b: 2, c: 3 };
const keys = _.keys(object);
console.log(keys); // Output: ["a", "b", "c"]

In this example, the _.keys function is used to extract the keys of an object and store them in an array. The resulting array contains the keys "a", "b", and "c", which correspond to the properties of the original object.

9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
};

// Return the number of elements in an object.
_.size = function(obj) {
  if (obj == null) return 0;
  return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};

// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
fork icon1
star icon1
watch icon2

+ 149 other calls in file

2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
};
entityMap.unescape = _.invert(entityMap.escape);

// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
  escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};

// Functions for escaping and unescaping strings to/from HTML interpolation.
fork icon0
star icon1
watch icon1

+ 22 other calls in file

198
199
200
201
202
203
204
205
206
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

108
109
110
111
112
113
114
115
116
117
};
formatter = new K.client.Formatter;

if(config.purge){
	purgeDB(K.schema, function(S){
		var tables = _.keys(schema);
		createTables(S, tables, loadFixtures);
	});
	
}
fork icon0
star icon1
watch icon4

+ 11 other calls in file

5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
fork icon0
star icon0
watch icon0

+ 35 other calls in file

80
81
82
83
84
85
86
87
88
89
async copyEntity(entity, changes = {}) {
    const excluded = ['_id', '__v', 'updated_at'];//, 'created_at', 'updated_at'];
    const attributesNames = this.pickSchema(excluded);
    const copiedEntity = _.pick(entity, attributesNames);

    const changedAttributesNames = _.keys(changes);
    const isChanged = changedAttributeName => changedAttributesNames.indexOf(changedAttributeName) > 0;
    const attributeExists = attributeName => attributesNames.indexOf(attributeName) >= 0;

    if (attributeExists('created_at') && !isChanged('created_at')) {
fork icon0
star icon0
watch icon0

139
140
141
142
143
144
145
146
147
148
             unibuildResult.pluginProviderPackageNames);
  });

  return {
    isopack: isopk,
    pluginProviderPackageNames: _.keys(pluginProviderPackageNames)
  };
};

// options.sourceArch is a SourceArch to compile.  Process all source files
fork icon0
star icon0
watch icon2

108
109
110
111
112
113
114
115
116
117
axis: {
    // shows labels on left when there are more than 10 columns
    rotated: this.data.length > 10,
    x: {
        type: 'category',
        categories: _.keys(this.data)
    }
},
legend: { show: false },
transition: { duration: 0 }
fork icon0
star icon0
watch icon2

+ 2 other calls in file

212
213
214
215
216
217
218
219
220
221
  } catch (error) {
    
  }
}

const keys = _.keys(modifier);
for(var i = 0; i < keys.length; i++ ){
    const k = keys[i];
    const v = modifier[k];
    var auditRecordsObject, db_new_value, db_previous_value, doc, field, new_value, previous_value;
fork icon0
star icon0
watch icon1

655
656
657
658
659
660
661
662
663
664
apiMocker.compareHashed = (filterDef, body) => {
  if (!(filterDef instanceof Object)) {
    // eslint-disable-next-line eqeqeq
    return filterDef == body;
  }
  const algo = _.keys(filterDef)[0];
  const hasher = crypto.createHash(algo);
  hasher.update(body);
  const digest = hasher.digest('hex');
  apiMocker.logger.warn(`Body hash ${algo}: ${digest}`);
fork icon0
star icon0
watch icon1

+ 3 other calls in file