Maps and Lodash map values at the facility
This solution uses _.transform(), and it is a little shorter. I'm not sure if this is 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, match them with the necessary 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);Just for completeness, here's 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);2: Object.entries &
IE, :
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);3: Object.keys/Object.entries Array.forEach
, Reduce. , .
const orig = {" a ":1, " b ":2};
let result = {};
Object.keys(orig).forEach(k => result[k.trim()] = orig[k] + 1);
console.log(result);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 that?
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>Using the abbreviation, you can:
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>the abbreviation is more familiar, but the IMO conversion seems more appropriate here.