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?
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 _.
Peter Chang. As the result of the article in jsperf.com _(2015)_shows that, Lodash performances faster than Native Javascript.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With