[英]How to trim both key and value from an array of objects using lodash
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.我如何使用 lodash
trim
方法来修剪键和值。
{
"Id": 11,
"name": "xxN"
}
Expected:预期的:
Does it have to use Lodash?它必须使用 Lodash 吗? With vanilla JavaScript:
香草 JavaScript:
result = Object.fromEntries(Object.entries(data).map(([key, value]) =>
[key.trim(), typeof value == 'string' ? value.trim() : value]))
For completeness, here's a Lodash solution using _.transform()
为了完整起见,这是一个使用
_.transform()
的 Lodash 解决方案
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/lodash@4.17.21/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.这有额外的好处,可以生产一个新的 object,其原型与您的原始原型相同,可能方便也可能不方便。
Using lodash trim method使用 lodash修剪方法
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/lodash@4.17.21/lodash.min.js"></script>
Vanilla js would be better if you had the support for it but with lodash如果你支持 Vanilla js 会更好但是有 lodash
var trimmed = _.fromPairs(
_.map(input, (value, key) => [
_.trim(key),
typeof value === "string" ? _.trim(value) : value
])
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.