Reputation: 5099
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
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
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