我正在尝试使用lodash的_.trim
删除键/值中的前导/尾随空格,如下所示:
var items = [
{"key": " Needs Trim 1 ", "value": " Needs Trim 2 "},
{"key": " Needs Trim 3 ", "value": " Needs Trim 4 "}
];
使用lodash修剪后看起来应该是这样的:
var items = [
{"key": "Needs Trim 1", "value": "Needs Trim 2"},
{"key": "Needs Trim 3", "value": "Needs Trim 4"}
];
我试过了:
var trimmedItems = _.map(items, _.trim);
console.log(trimmedItems); // outputs ["[object Object]", "[object Object]"]
但是我认为这不起作用,因为console.log(trimmedItems)
没有显示实际的物体,所以我不确定它们是否被修剪过。这是显示问题的fiddle,控制台也应该打开以查看问题。
任何想法如何让小提琴输出修剪过的lodash对象以确保它们被正确修剪?
答案 0 :(得分:8)
您可以使用each()
,如下所示。
_.each(items, o => _.each(o, (v, k) => o[k] = v.trim()))
第一个each
将迭代items
数组,嵌套的each
将迭代数组中对象的属性。要更新items
数组
o[k] = v.trim()
被使用。其中o
引用items
数组中的对象。
对于不支持ES6箭头功能的环境
_.each(items, function (o) {
_.each(o, function (v, k) {
o[k] = v.trim();
});
});
var items = [{
"key": " Needs Trim 1 ",
"value": " Needs Trim 2 "
}, {
"key": " Needs Trim 3 ",
"value": " Needs Trim 4 "
}];
_.each(items, o => _.each(o, (v, k) => o[k] = v.trim()))
console.log(items);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>
使用Vanilla JavaScript:
items.forEach(function(o) {
Object.keys(o).forEach(function(key) {
o[key] = typeof o[key] === 'string' ? o[key].trim() : o[key];
});
});
var items = [{
"key": " Needs Trim 1 ",
"value": " Needs Trim 2 "
}, {
"key": " Needs Trim 3 ",
"value": " Needs Trim 4 "
}];
items.forEach(function (o) {
Object.keys(o).forEach(function (key) {
o[key] = typeof o[key] === 'string' ? o[key].trim() : o[key];
});
});
console.log(items);
答案 1 :(得分:3)
您需要两个级别的映射。一个用于映射数组,另一个用于将对象的每个属性映射到其值的修剪版本:
_.map(items, function (obj) {
return _.fromPairs(_.map(obj, function (value, key) {
return [key, _.trim(value)]
}))
})
答案 2 :(得分:2)
映射是解决此问题的正确方法,但我的解决方案比meagar的
更合适
const items = [
{
key1: " Needs Trim 1 "
, key2: " Needs Trim 2 "
}, {
key1: " Needs Trim 3 "
, key2: " Needs Trim 4 "
}
];
const result = _.map(items, toTrimmedObject);
console.log(JSON.stringify(result, null, 2));
function toTrimmedObject(obj) {
return _.mapValues(obj, _.trim);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 3 :(得分:1)
您需要单独修剪key
和value
。
首先将_.trim()
应用于对象,然后天真地将对象转换为字符串,生成"[object Object]"
,然后修剪此字符串。
此外,不需要使用lodash,因为JavaScript本身已经提供了所有必要的功能:
var items = [{
"key": " Needs Trim 1 ",
"value": " Needs Trim 2 "
}, {
"key": " Needs Trim 3 ",
"value": " Needs Trim 4 "
}];
var out = items.map(function(item) {
item.key = item.key.trim();
item.value = item.value.trim();
return item;
});
console.log(out);
答案 4 :(得分:1)
修剪+删除对象中所有值的空白区域(包括嵌套对象)。跳过非字符串值和未定义的值。
const trimObject = (obj) => {
each(obj, (v, k) => {
if (v !== undefined) {
if (isObject(v)) {
obj[k] = trimObject(v)
} else {
obj[k] = typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : v
}
}
})
return obj
}