Home > OS >  How to trim both key and value from an array of objects using lodash
How to trim both key and value from an array of objects using lodash

Time:10-08

I have an array of objects like below.

 {
    "Id": 11,
    "name ": "xxN "
  }

How can I use lodash trim method to trim both key and value.

 {
    "Id": 11,
    "name": "xxN"
  }

Expected:

CodePudding user response:

Does it have to use Lodash? With vanilla JavaScript:

result = Object.fromEntries(Object.entries(data).map(([key, value]) => 
    [key.trim(), typeof value == 'string' ? value.trim() : value]))

CodePudding user response:

For completeness, here's a Lodash solution using _.transform()

const obj = {
  "Id": 11,
  "name ": "xxN "
}

const transformed = _.transform(obj, (result, value, key) => {
  result[key.trim()] = typeof value === "string" ? value.trim() : value
})

console.log(transformed)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

This has the added bonus of producing a new object with the same prototype as your original which may or may not be handy.

CodePudding user response:

Using lodash trim method

const arr = [
  {
    Id: 11,
    "name ": "xxN ",
  },
  {
    Id: 12,
    "name ": " yyK ",
  },
];

const result = arr.map((o) =>
  Object.fromEntries(
    Object.entries(o).map(([k, v]) => [k, typeof v === "string" ? _.trim(v) : v])
  )
);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

CodePudding user response:

Vanilla js would be better if you had the support for it but with lodash

var trimmed = _.fromPairs(
  _.map(input, (value, key) => [
    _.trim(key),
    typeof value === "string" ? _.trim(value) : value
  ])
);
  • Related