How to use the keys function from lodash

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

lodash.keys is a function that takes an object as input and returns an array of its own enumerable property names.

107
108
109
110
111
112
113
114
115
116
117


eb.on(eb.reloadWithMoreParams, function(params) {
  var existingParams = encodedParams ? Utils.decodeParams(encodedParams) : {};
  var combinedParams = _.extend({}, existingParams, params);
  var ep = Utils.encodeParams(combinedParams);
  if (!combinedParams || 0 === _.keys(combinedParams).length) {
    ep = "";
  }
  var path = document.location.pathname.match(/^((?!ep1_).)*/)[0];
  if (path[path.length - 1] === "/") {
fork icon125
star icon491
watch icon21

+ 3 other calls in file

1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861


// Machine page
app.get("/machines/:id", (req, res, next) => {
    db.machines.findByIdAsync(req.params.id)
        .then((mac) => {
            var projKeys = _.keys(mac.projects); // Extract project IDs
            projKeys = _.map(projKeys, db.toObjectID); // Map to MongoDB IDs
            db.projects.find({
                    _id: {
                        $in: projKeys
fork icon62
star icon180
watch icon22

+ 4 other calls in file

How does lodash.keys work?

lodash.keys is a utility function that takes an object and returns an array of its own enumerable property names.

Internally, it uses the Object.keys() method to extract the keys of the object and returns them as an array. If the object passed to lodash.keys is null or undefined, an empty array is returned.

141
142
143
144
145
146
147
148
149
150
if (!_.isPlainObject(value)) {
    throw new Error('"takeScreenshotOnFails" must be an object');
}

const allowedProps = ['assertViewFail', 'testFail'];
const unknownProps = _.keys(value).filter(prop => !allowedProps.includes(prop));

if (unknownProps.length) {
    throw new Error(`"takeScreenshotOnFails" contains unknown properties: ${unknownProps}. Allowed: ${allowedProps}.`);
}
fork icon56
star icon556
watch icon11

+ 2 other calls in file

532
533
534
535
536
537
538
539
540
541
542


function lookupBitField(field, value) {
  if (!field.value2name) {
    field.value2name = {};
    field.EnumBitValues.forEach(function(enumPair) {
      var key = _.keys(enumPair)[0]
      field.value2name[Number(key)] = enumPair[key]
    })
  }
  return (field.value2name[value]);
fork icon26
star icon65
watch icon14

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, lodash.keys is used to get an array of keys from an object. The object variable contains three key-value pairs, and lodash.keys is used to extract the keys from this object into an array. The resulting array is then logged to the console, which will output ["a", "b", "c"].

109
110
111
112
113
114
115
116
117
118
 */
function difference(fromObject, toObject) {
  const changes = {}
  const buildPath = (_path, key) => _.isUndefined(_path) ? key : `${_path}.${key}`
  const walk = (_fromObject, _toObject, _path) => {
    for (const key of _.keys(_fromObject)) {
      const currentPath = buildPath(_path, key)
      if (!_.has(_toObject, key)) {
        changes[currentPath] = { from: _.get(_fromObject, key) }
      }
fork icon1
star icon4
watch icon4

+ 18 other calls in file

786
787
788
789
790
791
792
793
794
795

logger.debug('Result from parsePayload:')
logger.debug(JSON.stringify(saveDraftContestDTO))

let metaValue
for (const metadataKey of _.keys(constants.supportedMetadata)) {
  try {
    metaValue = constants.supportedMetadata[metadataKey].method(message.payload, constants.supportedMetadata[metadataKey].defaultValue)
    if (metaValue !== null && metaValue !== '') {
      logger.info(`Setting ${constants.supportedMetadata[metadataKey].description} to ${metaValue}`)
fork icon6
star icon3
watch icon35

+ 7 other calls in file

1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
  }
}
model.xvalidate = new _this.XValidate();
if ('sites' in model) _this.LogInit_WARNING('Model ' + model.id + ' had previous "sites" attribute - overwritten by system value');
if(model.roles){
  var roleids = _.keys(model.roles);
  //Resolve '*' roles
  for(let i=0;i<roleids.length;i++){
    var role = roleids[i];
    if(_.isString(model.roles[role])){
fork icon5
star icon5
watch icon2

102
103
104
105
106
107
108
109
110
111
112
113
    sub_menu: [
      //{ "menu_name": "Admin/SysUser_Listing", "menu_desc": "System Users", "menu_cmd": "%%%NAMESPACE%%%Admin/SysUser_Listing", "menu_subcmd": null, "menu_seq": 80000, "menu_id": 80000, "menu_parent_name": "Admin", "roles": { "main": [ "SYSADMIN", "DEV" ] } },      { "menu_name": "Admin/Param_User_Listing", "menu_desc": "User Settings", "menu_cmd": "%%%NAMESPACE%%%Admin/Param_User_Listing", "menu_subcmd": null, "menu_seq": 80081, "menu_id": 80081, "menu_parent_name": "Admin", "roles": { "main": [ "SYSADMIN", "DEV" ] } },
    ],
  };


  this._validProperties = _.keys(this);
}
jsHarmonyFactoryConfig.prototype = new jsHarmonyConfig.Base();


jsHarmonyFactoryConfig.prototype.Merge = function(config, jsh, sourceModuleName){
fork icon1
star icon2
watch icon2

21
22
23
24
25
26
27
28
29
30
            value:值,    若该参数校验失败,则用value的值作为该参数的值填入校验结果json
          }
*/
const getArguments = function (args, rule) {
    let result = {};
    let keys = _.keys(rule);
    let i = 0;
    let j = 0;
    //参数和规则一一对应检测并赋值
    //当参数不符合对应规则,并且该规则是可选项时,就用当前参数去对应下一个规则
fork icon0
star icon2
watch icon0

+ 4 other calls in file

97
98
99
100
101
102
103
104
105
106
            break;
    }
} else if (_.isObject(rule.type) && _.isObject(value)) {
    //类型如果是json,则判断对象是否属于同类json
    //判断方式是逐个检查json成员是否符合对应规则
    let keys = _.keys(rule.type);
    for (let i = 0; i < keys.length; i++) {
        if (!check(value[keys[i]], rule.type[keys[i]])) {
            return false;
        }
fork icon0
star icon2
watch icon0

+ 4 other calls in file

150
151
152
153
154
155
156
157
158
TypeUtils.assert(socket.postJson.args[0][0], "string");
TypeUtils.assert(socket.postJson.args[0][1], "{}");
TypeUtils.assert(socket.postJson.args[0][2], "{input: {events: Array.<string>}}");

assert.strictEqual( socket.postJson.args[0][0], apiPath);
assert.strictEqual( _.keys(socket.postJson.args[0][1]).length, 0);

assert.strictEqual( socket.postJson.args[0][2].input.events.length, 1);
assert.strictEqual( socket.postJson.args[0][2].input.events[0], eventName);
fork icon0
star icon1
watch icon3

+ 5 other calls in file

249
250
251
252
253
254
255
256
257
258

getContentTypes = (requestInfo, extraContentTypes) =>
  _.uniq(
    _.compact([
      ...(extraContentTypes || []),
      ..._.flatten(_.map(requestInfo, (requestInfoData) => requestInfoData && _.keys(requestInfoData.content))),
    ]),
  );

getContentKind = (contentTypes) => {
fork icon236
star icon0
watch icon12

671
672
673
674
675
676
677
678
679
680
681
682
683
console.log(invertBy); // => { '1': ['a', 'c'], '2': ['b'] }


const invoke = _.invoke({ 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }, 'a[0].b.c.slice', 1, 3);
console.log(invoke); // => [2, 3]


const keys = _.keys({ 'a': 1, 'b': 2 });
console.log(keys); // => ['a', 'b']


const keysIn = _.keysIn({ 'a': 1, 'b': 2 });
console.log(keysIn); // => ['a', 'b']
fork icon0
star icon1
watch icon1

+ 15 other calls in file

2201
2202
2203
2204
2205
2206
2207
2208
2209
2210

// Clear this schema from the inheritance cache
delete this._inheritanceCache[typeid];

// Remove the typeid from the constructor cache
var registeredConstructors = _.keys(this._typedPropertyConstructorCache);
for (var i = 0; i < registeredConstructors.length; i++) {
	if (registeredConstructors[i].substr(0, typeid.length) === typeid) {
		delete this._typedPropertyConstructorCache[registeredConstructors[i]];
	}
fork icon439
star icon0
watch icon75

2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns an array of property names.
 * @example
 *
 * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
 * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
 */
var keys = !nativeKeys ? shimKeys : function(object) {
  if (!isObject(object)) {
fork icon73
star icon711
watch icon29

234
235
236
237
238
239
240
241
242
243
module.exports.juxt                = _.juxt;
module.exports.kebabCase           = _.kebabCase;
module.exports.keep                = _.keep;
module.exports.keepIndexed         = _.keepIndexed;
module.exports.keyBy               = _.keyBy;
module.exports.keys                = _.keys;
module.exports.keysIn              = _.keysIn;
module.exports.kv                  = _.kv;
module.exports.last                = _.last;
module.exports.lastIndexOf         = _.lastIndexOf;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

223
224
225
226
227
228
229
230
231
var ZestIcons = require(packagePath(package.name, 'javascript', package.bundle))
var svg = []
var maxCol = 20
var width = 24 * maxCol
var iconsByCategory = _.groupBy(ZestIcons.all, 'category')
var categoryUids = _.keys(iconsByCategory).sort().reverse()
var categories = []
var accumulatedWidth = ((maxCol * 2) + 1) * 24
var accumulatedHeight = (categoryUids.length + 1) * 24
fork icon1
star icon11
watch icon1

+ 15 other calls in file

108
109
110
111
112
113
114
115
116
117
ctx.integrations = pick(integrations, keys(ctx.enabled));

const versions = {
  core: coreVersion,
  cdn: settings.cdnVersion || null,
  integrations: pick(integrationVersions, keys(ctx.enabled))
};

ctx.plan = JSON.stringify({});
ctx.integrations = JSON.stringify(ctx.integrations);
fork icon144
star icon0
watch icon2

+ 3 other calls in file

88
89
90
91
92
93
94
95
96
97

console.log('-- Bundling -------------');

var promises = [];
var completed = [];
groups = (groups) ? groups : _.keys(_bundles);
groups = (_.isArray(groups)) ? groups : [groups];

_.forEach(groups, function (groupName) {
    promises.push(async.asyncify(function () {
fork icon4
star icon3
watch icon2

+ 7 other calls in file

2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
      delete widgetsByType[type];
    }
  }
}

for (const type of _.keys(widgetsByType)) {
  const manager = self.apos.area.getWidgetManager(type);
  if (!manager) {
    self.apos.area.warnMissingWidgetType(type);
  }
fork icon540
star icon0
watch icon0

+ 2 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)