How to use the keyBy function from lodash

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

272
273
274
275
276
277
278
279
280
try {
  const notifications = await new AV.Query('notification')
    .containedIn('ticket', tickets)
    .equalTo('user', req.user)
    .find({ user: req.user })
  notificationMap = _.keyBy(notifications, (notification) => notification.get('ticket')?.id)
} catch (error) {
  console.error(error)
}
fork icon60
star icon277
watch icon27

+ 2 other calls in file

233
234
235
236
237
238
239
240
241
242
module.exports.join                = _.join;
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;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

326
327
328
329
330
331
332
333
334
335
    const iirisCallback = (x) => String(x % 10)
    const lodashCallback = (x) => String(x % 10)
    const ramdaCallback = (x) => String(x % 10)
    return {
      iiris: () => A.indexBy(iirisCallback, array),
      lodash: () => _.keyBy(array, lodashCallback),
      ramda: () => R.indexBy(ramdaCallback, array),
    }
  },
},
fork icon1
star icon31
watch icon0

88
89
90
91
92
93
94
95
96
97
 * Utility to build an object from a transformed metadata array of objects so you can reference properties
 * by key rather than array index. Helpful when the array length changes.
 * @returns {{}}
 */
function buildMetaDataObj(collection) {
  return keyBy(collection, (elem) => {
    return snakeCase(elem.label)
  })
}

fork icon8
star icon8
watch icon0

73
74
75
76
77
78
79
80
81
82
        .map(function readPackageJson(packageName) {
            const absolutePath = join(packagePath, packageName);
            return processPackage(absolutePath, packageName);
        })
        .then(function (packages) {
            return _.keyBy(packages, 'name');
        });
};

/**
fork icon0
star icon2
watch icon0

25
26
27
28
29
30
31
32
33
34
    limit: uids.length,
  },
})
.then(({ data }) => {
  debug('resolveTextReuseClusters data:', data.length)
  return lodash.keyBy(data, 'textReuseCluster.id')
})
.catch((err) => {
  console.error('hook resolveTextReuseClusters ERROR')
  console.error(err)
fork icon1
star icon0
watch icon0

242
243
244
245
246
247
248
249
250
251
252
253
254
console.log(includes); // => true


const invokeMap = _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
console.log(invokeMap); // => [[1, 5, 7], [1, 2, 3]]


const keyBy = _.keyBy([{ 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }], object => String.fromCharCode(object.code));
console.log(keyBy); // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }


const map = _.map([4, 8], n => n * n);
console.log(map); // => [16, 64]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

64
65
66
67
68
69
70
71
72
73
74
75
            [username]: { username, first_name, last_name }
        };
    }


    const resolvedUsers = await P.map(usernames, username => users.getUser(username));
    return _.keyBy(resolvedUsers, 'username');
};


exports.getUser = function (resolvedUsersById, username) {
    if (_.has(resolvedUsersById, username)) {
fork icon17
star icon1
watch icon8

+ 4 other calls in file

32
33
34
35
36
37
38
39
40
41
42
43
]


const regionsIndex = keyBy(regions, 'code')
const departementsIndex = keyBy(departements, 'code')
const communesActuellesIndex = keyBy(communesActuelles, 'code')
const communesDelegueesIndex = keyBy(communesDeleguees, 'code')


const anciensCodesIndex = new Map()
for (const commune of communesActuelles) {
  const anciensCodes = commune.anciensCodes || []
fork icon3
star icon7
watch icon3

+ 7 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26
27
const BAL = require('./strategies/bal/index.cjs')


const prepareBalData = require('./sources/bal.cjs')
const importFromApiDepot = require('./import-from-api-depot.cjs')


const locauxAdressesIndex = keyBy(communesLocauxAdresses, 'codeCommune')


async function getSourceData(sourceName, codeCommune) {
  const adresses = await source(sourceName).getAdresses(codeCommune)
  const prepareData = require(`./sources/${sourceName}.cjs`)
fork icon3
star icon7
watch icon3

197
198
199
200
201
202
203
204
205
206
   any config-file elements per platform that have the same target and parent, the last config-file element is used.
 */
getConfigFilesByTargetAndParent: function (platform) {
  var configFileData = this.getConfigXml().findall('platform[@name=\'' + platform + '\']/config-file');

  return _.keyBy(configFileData, function (item) {
    var parent = item.attrib.parent;
    //if parent attribute is undefined /* or */, set parent to top level elementree selector
    if (!parent || parent === '/*' || parent === '*/') {
      parent = './';
fork icon0
star icon0
watch icon1

505
506
507
508
509
510
511
512
513
514
  const users = await stelace.users.list({
    id: usersIds,
    nbResultsPerPage: 100
  })

  const usersById = keyBy(users, 'id')
  keys.forEach(key => {
    this.syncedData.users[key] = usersById[this.syncedData.users[key].id]
  })
}
fork icon0
star icon0
watch icon1

+ 2 other calls in file

134
135
136
137
138
139
140
141
142
143
144
145
    const li = l.reduce((result, x) => {
        return [...result, { id: x }];
    }, []);
    console.log(li);   // [ { id: 1 }, { id: 2 }, { id: 3 } ]


    const list = _.keyBy(li, 'id');
    console.log(list); // { '1': { id: 1 }, '2': { id: 2 }, '3': { id: 3 } }
}


function test_reduce() {
fork icon0
star icon0
watch icon0

133
134
135
136
137
138
139
140
141
142
143
144
145
        return [...m, { id: m.length + 1, weight: x }];
    }, []);


    console.log(l); // [{ id: 1, weight: 100 }, { id: 2, weight: 300 }, { id: 3, weight: 600 }]


    const d = _.keyBy(l, 'id');
    console.log(d); // { '1': { id: 1, weight: 100 }, '2': { id: 2, weight: 300 }, '3': { id: 3, weight: 600 } }
}


function test_findIndex() {
fork icon0
star icon0
watch icon0

+ 4 other calls in file

942
943
944
945
946
947
948
949
950
951
    ...findQuery
  },
  attributes: [...facets, [Sequelize.fn('count', Sequelize.col(facets[0])), 'count']],
  group: [...facets]
}).then((result) => {
    const apiRes = _.keyBy(_.map(result, 'dataValues'), 'rootorg_id');

    const orgIds = _.map(apiRes, 'rootorg_id');
    if (_.isEmpty(result) || _.isEmpty(orgIds)) {
      loggerService.exitLog({responseCode: 'OK'}, logObject);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

126
127
128
129
130
131
132
133
134
135

    return fontmin
}

mergeAssetsAndFiles(group, files) {
    const byExtension = _.keyBy(files, 'extname')

    const first = group[0];

    // log('mergeAssetsAndFiles', group);
fork icon0
star icon0
watch icon2

290
291
292
293
294
295
296
297
298
299
  return _.sortBy(this._rawSheets, 'index');
}

get sheetsByTitle() {
  this._ensureInfoLoaded();
  return _.keyBy(this._rawSheets, 'title');
}

async addSheet(properties = {}) {
  // Request type = `addSheet`
fork icon0
star icon0
watch icon1

+ 3 other calls in file

703
704
705
706
707
708
709
710
711
712
} else {
	userIds = [codemark.get('creatorId')];
}

postUsers = await this.data.users.getByIds(userIds);
const usersById = keyBy(postUsers, function (u) {
	return u.get('_id');
});
const codemarkUser = usersById[codemark.get('creatorId')];
let blocks = [
fork icon0
star icon0
watch icon1

+ 3 other calls in file

44
45
46
47
48
49
50
51
52
53
  log.debug('Loaded ignore words from "' + ignoreWordsPath + '"');
  log.silly(wordsToIgnore);

}

areasToSearch = _.keyBy(this.areasToSearch);
propertiesToIgnore = _.keyBy(this.propertiesToIgnore);
log.debug('Properties to ignore', propertiesToIgnore);
docTypesToIgnore = _.keyBy(this.docTypesToIgnore);
log.debug('Doc types to ignore', docTypesToIgnore);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

171
172
173
174
175
176
177
178
179
180
		$in: usr
	}
})
.lean()
.then((users) => {
	let u = _.keyBy(users, 'id');
	_.forEach(res, (entry) => {
		entry.user = u[entry.user_id];
		return entry;
	});
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

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