v + ...">

Maps and Lodash map values ​​at the facility

My code is:

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 way for Lodasha to do this?

+10
source share
4 answers

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>
Run codeHide result

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);
Run codeHide result

+12
source

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);
Run codeHide 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);
Hide 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);
Hide result

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

+2

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>
Run codeHide result
+1
source

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>
Run codeHide result

the abbreviation is more familiar, but the IMO conversion seems more appropriate here.

+1
source

Source: https://habr.com/ru/post/1682434/


All Articles