Lodash map keys and values on an object

Viewed 42289

My code:

const orig = {" a ":1, " b ":2}
let result = _.mapKeys(_.mapValues(orig, (v) => v + 1), (v, k) => k.trim())

actual and desired result = { "a": 2, "b": 3 }

But is there a better Lodashy way of doing this?

5 Answers

Just for completeness, this is how you would do it without lodash:

Solution 1: Object.keys & reduce

const orig = {" a ":1, " b ":2};
let result = Object.keys(orig).reduce((r, k) => {
  r[k.trim()] = orig[k] + 1;
  return r;
}, {})
console.log(result);

Solution 2: Object.entries & reduce

If your okay with using a polyfill for IE, you can also do this:

const orig = {" a ":1, " b ":2};
let result = Object.entries(orig).reduce((r, [k, v]) => {
  r[k.trim()] = v + 1;
  return r;
}, {})
console.log(result);

Solution 3: Object.keys/ Object.entries with Array.forEach

One of the main issues with the above approaches is that you need to return result with reduce statements. It's not a big issue, but adds to the number of lines. An alternative approach is as follows

const orig = {" a ":1, " b ":2};
let result = {};
Object.keys(orig).forEach(k => result[k.trim()] = orig[k] + 1);
console.log(result);

or

const orig = {" a ":1, " b ":2};
let result = {};
Object.entries(orig).forEach(([k, v]) => result[k.trim()] = v + 1);
console.log(result);

You could use a good ol' for in loop as it looks cleaner

const orig = {" a ":1, " b ":2};
let result = {};
for (const key in orig) {
  result[key.trim()] = orig[key] + 1
}
// result {a: 2, b: 3} 

you could even make it a one liner.. :)

const orig = { ' a ': 1, ' b ': 2 };
let result = {}; for (const key in orig) result[key.trim()] = orig[key] + 1;
// result {a: 2, b: 3} 
Related