Wonka Wonka - 3 months ago 12
Javascript Question

lodash - How to _.trim an array of objects?

I am trying to use lodash's

_.trim
to remove leading/trailing whitespace in the key/value like this:

var items = [
{"key": " Needs Trim 1 ", "value": " Needs Trim 2 "},
{"key": " Needs Trim 3 ", "value": " Needs Trim 4 "}
];


It should look like this after trimming with lodash:

var items = [
{"key": "Needs Trim 1", "value": "Needs Trim 2"},
{"key": "Needs Trim 3", "value": "Needs Trim 4"}
];


I tried this:

var trimmedItems = _.map(items, _.trim);
console.log(trimmedItems); // outputs ["[object Object]", "[object Object]"]


But I don't think that worked, as the
console.log(trimmedItems)
doesn't show the actual objects, so I am not sure if they are trimmed. Here is a fiddle showing the issue, console should be open to see the issue as well.

Any idea how to get the fiddle to output the trimmed lodash objects to ensure they are trimmed correctly?

Answer

You can use each() as follow.

_.each(items, o => _.each(o, (v, k) => o[k] = v.trim()))

The first each will iterate over items array and the nested each will iterate over the properties in the object in the array. To update he original value in the items array

o[k] = v.trim()

is used. Where o is referencing to the object inside the items array.

For environments where ES6 Arrow function is not supported

_.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>

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

Comments