How to use the mapValues function from lodash

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

lodash.mapValues is a function that creates a new object by iterating over the properties of an existing object and applying a function to each property's value.

3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
 *   'fred': { 'name': 'fred', 'age': 40 },
 *   'pebbles': { 'name': 'pebbles', 'age': 1 }
 * };
 *
 * // using "_.pluck" callback shorthand
 * _.mapValues(characters, 'age');
 * // => { 'fred': 40, 'pebbles': 1 }
 */
function mapValues(object, callback, thisArg) {
  var result = {};
fork icon73
star icon711
watch icon29

+ 3 other calls in file

249
250
251
252
253
254
255
256
257
258
module.exports.lteContrib          = _.lteContrib;
module.exports.map                 = _.map;
module.exports.mapArgs             = _.mapArgs;
module.exports.mapArgsWith         = _.mapArgsWith;
module.exports.mapKeys             = _.mapKeys;
module.exports.mapValues           = _.mapValues;
module.exports.mapcat              = _.mapcat;
module.exports.matches             = _.matches;
module.exports.matchesProperty     = _.matchesProperty;
module.exports.max                 = _.max;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.mapValues work?

lodash.mapValues takes two arguments: an object and a function. For each property of the object, lodash.mapValues applies the function to the property's value, and uses the function's return value as the new value for that property in the resulting object. The resulting object has the same keys as the original object, but with the values transformed by the provided function. Here is the general syntax for lodash.mapValues: css Copy code {{{{{{{ class="!whitespace-pre hljs language-css">_.mapValues(object, [iteratee=_.identity]) object: The object to iterate over. iteratee (optional): The function to apply to each value in the object. If not provided, the identity function (_.identity) is used. lodash.mapValues does not modify the original object. Instead, it creates a new object with the same keys and transformed values.

35
36
37
38
39
40
41
42
43
44
45
const saveUser = (redis, category, audience, user) => redis
  .pipeline()
  .sadd(USERS_INDEX, user.id)
  .hmset(
    redisKey(user.id, category, audience),
    ld.mapValues(user[category], JSON.stringify.bind(JSON))
  )
  .exec();


function listRequest(filter, criteria = 'username') {
fork icon13
star icon8
watch icon7

+ 9 other calls in file

58
59
60
61
62
63
64
65
66
67

return {
  numero,
  suffixe,
  lieuDitComplementNom: lieuDitComplementNom ? beautifyUppercased(lieuDitComplementNom) : null,
  lieuDitComplementNomAlt: lieuDitComplementNomAlt ? mapValues(nom => beautifyUppercased(nom)) : {},
  parcelles: parcelles || [],
  sources: ['bal'],
  dateMAJ,
  certifie: forceCertification || certificationCommune,
fork icon3
star icon7
watch icon3

Ai Example

1
2
3
4
5
6
7
8
const originalObject = { a: 1, b: 2, c: 3 };

const transformedObject = _.mapValues(originalObject, (value) => {
  return value * 2;
});

console.log(transformedObject);
// Output: { a: 2, b: 4, c: 6 }

In this example, lodash.mapValues takes an object with three properties { a: 1, b: 2, c: 3 } and applies a function that doubles the value of each property. The resulting object is { a: 2, b: 4, c: 6 }. The original object is not modified.

193
194
195
196
197
198
199
200
201
202
var rules = this.getStyleProp(ruleName);
var div = document.createElement('div');
_.each(rules, function (value, attribute) {
    div.style[attribute] = toPx(value, attribute);
});
var result = _.mapValues(div.style, function (value) {
    return toNum(value);
});

result.widthIncludesPadding = function () {
fork icon0
star icon7
watch icon19

299
300
301
302
303
304
305
306
307
308
    }
    if (_.isObject(obj)) {
        // First map object itself
        const res = mapping(obj);
        // Then map values
        return _.mapValues(res, (value) => (0, exports.mapObjectTree)(value, mapping));
    }
    return obj;
};
exports.mapObjectTree = mapObjectTree;
fork icon3
star icon4
watch icon3

+ 2 other calls in file

50
51
52
53
54
55
56
57
58
59
slave.processedManifest = (function() {
    var devGlobs = slave.json.dev;
    var injectionByBuildFiles = slave.json.build;

    // gather slave dev files
    return _.mapValues(injectionByBuildFiles, function(injectTasks, buildFile) {
        return _.flatten(injectTasks.map(function (injectTaskName) {
            if (!devGlobs.hasOwnProperty(injectTaskName))
                return [];
            else
fork icon3
star icon2
watch icon0

674
675
676
677
678
679
680
681
682
683
    const ramdaCallback = (x) => x + 1
    const lodashCallback = (x) => x + 1
    return {
      iiris: () => O.mapValues(iirisCallback, obj),
      ramda: () => R.map(ramdaCallback, obj),
      lodash: () => _.mapValues(obj, lodashCallback),
    }
  },
},
{
fork icon1
star icon31
watch icon0

128
129
130
131
132
133
134
135
136
137
138
    : logger.debug(level, ...args));
}


function getCustomProperties(logger) {
  return Object.assign(
    _.mapValues(
      _.pick(
        logger,
        'log',
        'add',
fork icon2
star icon4
watch icon4

+ 4 other calls in file

680
681
682
683
684
685
686
687
688
689
690
691
692
console.log(keysIn); // => ['a', 'b']


const mapKeys = _.mapKeys({ 'a': 1, 'b': 2 }, (value, key) => key + value);
console.log(mapKeys); // => { 'a1': 1, 'b2': 2 }


const mapValues = _.mapValues({ 'a': 1, 'b': 2 }, (value, key) => key + value);
console.log(mapValues); // => { 'a': 'a1', 'b': 'b2' }


const merge = _.merge({ 'a': [{ 'b': 1 }, { 'd': 2 }] }, { 'a': [{ 'c': 3 }, { 'e': 4 }] });
console.log(merge); // => { 'a': [{ 'b': 1, 'c': 3 }, { 'd': 2, 'e': 4 }] }
fork icon0
star icon4
watch icon0

+ 15 other calls in file

77
78
79
80
81
82
83
84
85
86
  quotes,
  jsesc(string, {quotes, wrap: true}),
])
quotedStrings = _.fromPairs(quotedStrings)

let lengthMap = _.mapValues(quotedStrings, x => x.length)

let lengthSorted = _.toPairs(lengthMap).sort(([, a], [, b]) => a - b)
let [short, mid] = lengthSorted
let lengthSet = new Set(_.values(lengthMap))
fork icon0
star icon2
watch icon0

210
211
212
213
214
215
216
217
218
219
if (data.length == 0) {
  return res.status(400).json({
    message: 'Không tìm thấy dữ liệu',
  });
} else {
  let value = _.mapValues(data, '_id');
  for (let i = 0; i < Object.keys(value).length; i++) {
    let dataList = {};
    Room.findById(value[i]).exec(async (err, data) => {
      if (err || !data) {
fork icon0
star icon1
watch icon1

+ 4 other calls in file

1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
            timeSegments: timeSegmentsTemplate,
        },
    }
};

workScheduleTemplate.weekDays = lodash.mapValues(workScheduleTemplate.weekDays, (weekDay) => {
    weekDay.timeSegments = lodash.map(weekDay.timeSegments, (timeSegment) => {
        timeSegment.maxHours = timeSegment.end - timeSegment.start
        timeSegment.start = mToTime(timeSegment.start)
        timeSegment.end = mToTime(timeSegment.end)
fork icon0
star icon1
watch icon0

+ 2 other calls in file

681
682
683
684
685
686
687
688
689
690
function runHook(className, hookType, data) {
  let hook = getHook(className, hookType);
  if (hook) {
    const hydrate = (rawData) => {
      const modelData = Object.assign({}, rawData, { className });
      const modelJSON = _.mapValues(modelData,
        // Convert dates into JSON loadable representations
        value => ((value instanceof Date) ? value.toJSON() : value)
      );
      return Parse.Object.fromJSON(modelJSON);
fork icon0
star icon0
watch icon2

+ 18 other calls in file

198
199
200
201
202
203
204
205
206
207
if(_.isNull(item)) {
  return null;
}

var formatter = function (data) {
  var map = _.mapValues;

  if(_.isArray(data)) {
    map = _.map;
  }
fork icon0
star icon0
watch icon1

74
75
76
77
78
79
80
81
82
83
84
85
    write(accum);
  });
}


function write(agg) {
  var incragg = _.mapValues(agg, (v) => _.sortBy(v, 'time'));


  Promise.all(_.map(incragg, function (data, key) {
    var prev = {};
    var output = _.chain(data).map(function (item) {
fork icon0
star icon0
watch icon1

+ 26 other calls in file

109
110
111
112
113
114
115
116
117
118
    tasks: stelace.tasks.list({ nbResultsPerPage: 100 }),
    transactions: stelace.transactions.list({ nbResultsPerPage: 100 }),
    users: stelace.users.list({ nbResultsPerPage: 100 }),
    workflows: stelace.workflows.list(),
  })
  this.syncedData = mapValues(this.existingData, () => ({}))
  this.referencedData = mapValues(this.existingData, objects => keyBy(objects, getObjectAlias))
}

/**
fork icon0
star icon0
watch icon1

688
689
690
691
692
693
694
695
696
697
  //get the map via model
  sortKeyMap = this.getFieldNameMap(data.modelName, data.models);
}
if (data.prefix) {
  // add table alias or prefix for keyMap
  sortKeyMap = _.mapValues(sortKeyMap, (val) => data.prefix + val);
}

let orderByString = data.sortKeys
  .map(function (sortKey) {
fork icon0
star icon0
watch icon3

+ 51 other calls in file

47
48
49
50
51
52
53
54
55
56

if (_.isEmpty(contentApiActions)) {
  return acc;
}

acc[controllerName] = _.mapValues(contentApiActions, () => {
  return {
    enabled: defaultEnable,
    policy: '',
  };
fork icon0
star icon0
watch icon1

469
470
471
472
473
474
475
476
477
478
479
480
481
}


function processHourlyData(rows) {
  const hoursMap = _.groupBy(rows, (row) => row.hour || row.hour2 || 0);


  const resultMap = _.mapValues(hoursMap, (dateRows, hour) => {
    const datesMap = _.groupBy(dateRows, (row) => row.date || row.date2);


    const dates = _.map(datesMap, (items, date) => {
      return {
fork icon0
star icon0
watch icon1

+ 6 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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