Lodash map keys and values on an object
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);
How about something like this?
const orig = {" a ":1, " b ":2};
function test(object) {
let out = {};
_.forEach(object, function(value, key) {
out[key.trim()] = value + 1;
});
return out;
}
console.log(test(orig));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
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);
Using reduce you can do:
var obj = {" a ":1, " b ":2}
result = _.reduce(obj, (result, v, k) => {
result[k.trim()] = v + 1
return result
}, {})
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@latest/lodash.min.js"></script>
reduce is more familiar but IMO transform seems more appropriate here