user2024080
user2024080

Reputation: 5099

How to trim the object value and returned with new object?

I am tying to trim the values from a object, but not works.

var obj = {'name' : 'arif', 'city':'chennai'};

var y = Object.keys(obj).reduce(function (obj, key) {
    return obj[key] = String(obj[key]).trim();
}, {});

console.log(y); //undefined

any one help me here?

Upvotes: 0

Views: 99

Answers (2)

Jagjeet Singh
Jagjeet Singh

Reputation: 1572

You can use Object.keys() method to iterate the object properties and update its values:

var obj = {'name' : 'arif   ', 'city':'  chennai'};

Object.keys(obj).forEach(k => obj[k] = obj[k].trim());
console.log(obj);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371049

You need to return the accumulator for the next iteration at the bottom of each callback, You should also use a different variable name for the object you're creating and the original obj, so that you can reference both separately:

var obj = {'name' : 'arif   ', 'city':'chennai'};

var newObj = Object.keys(obj).reduce(function (newObj, key) {
    newObj[key] = obj[key].trim();
    return newObj;
}, {});

console.log(newObj);

Another option is to use Object.fromEntries, which looks significantly cleaner IMO (very modern environment or polyfill required):

var obj = {'name' : 'arif   ', 'city':'chennai'};

var newObj = Object.fromEntries(
  Object.entries(obj)
    .map(([key, val]) => [key, val.trim()])
);

console.log(newObj);

Upvotes: 1

Related Questions