javascript:修剪对象的所有属性 [英] javascript : trim all properties of an object

查看:80
本文介绍了javascript:修剪对象的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法修剪对象的所有属性?换句话说,我可以更改它吗?

Is there a way to trim all properties of an object? In other words, can I change that:

{a: ' a', b: 'b ', c: ' c '}

对此:

{a: 'a', b: 'b', c: 'c'}

似乎我无法映射对象,那么如何将函数应用到所有属性以获取对象呢?

It seems I can't map an object, so how can I apply a function to all properties an get the object back?

推荐答案

您可以使用

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

Object.keys(obj).map(k => obj[k] = obj[k].trim());

演示:

var obj = {
  a: ' a',
  b: 'b ',
  c: ' c '
};

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

如果您的object值可以是其他数据types的数据(不仅是strings),则可以添加检查以避免在非strings上调用.trim().

If your object values can be of other data types(not only strings), you can add a check to avoid calling .trim() on non strings.

Object.keys(obj).map(k => obj[k] = typeof obj[k] == 'string' ? obj[k].trim() : obj[k]);

这篇关于javascript:修剪对象的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆