Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash map keys and values on an object

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?

like image 251
danday74 Avatar asked Jul 27 '17 18:07

danday74


People also ask

Does Lodash work with maps?

Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. map() method creates an array of values by running each element in collection through the iteratee. There are many lodash methods that are guarded to work as iteratees for methods like _.

Is Lodash map faster than native?

Peter Chang. As the result of the article in jsperf.com _(2015)_shows that, Lodash performances faster than Native Javascript.

What is _ get?

Overview. The _. get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

How do you compare objects in Lodash?

isEqual() Method. The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.


1 Answers

This solution uses _.transform(), and it's a bit shorter. I'm not sure that it's better than your functional solution.

const orig = {" a ": 1, " b ": 2 };

const result = _.transform(orig, (r, v, k) => {
  r[k.trim()] = v + 1; 
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Without lodash I would use Object.entries() to extract the key and value, map them to the required forms, and then use Object.fromEntries() to convert back to an object:

const orig = {" a ": 1, " b ": 2 };

const result = Object.fromEntries(Object.entries(orig).map(([k, v]) => [k.trim(), v + 1]));

console.log(result);
like image 50
Ori Drori Avatar answered Oct 08 '22 17:10

Ori Drori