1

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:

4
  • what is your expected result? Commented Oct 8, 2021 at 3:44
  • added the expected section Commented Oct 8, 2021 at 3:47
  • what is difference here? Commented Oct 8, 2021 at 3:47
  • after "name ": "xxN " this is the space that I don't want Commented Oct 8, 2021 at 3:48

4 Answers 4

4

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]))
Sign up to request clarification or add additional context in comments.

4 Comments

looks promising. But I am using node 10 for my project and getting TypeError: Object.fromEntries is not a function, this error
@Nick Node 10 does not support Object.fromEntries. You have to upgrade to Node 14.
Yes @Spectric, Thats why I was looking for lodash. Can't upgrade the project to node 14. few things might break. 😔
@Spectric I assume he can't upgrade at all.
2

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.

Comments

0

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>

Comments

0

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
  ])
);

2 Comments

Do you need _.toPairs? Doesn't _.map() work with objects?
@Barmar Good call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.