如何将对象中的所有属性值转换为字符串类型? [英] How do I convert all property values in an object to type string?

查看:37
本文介绍了如何将对象中的所有属性值转换为字符串类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个对象,该对象包含的属性值为字符串类型或数字类型.一些属性是嵌套对象,并且这些嵌套对象还包含值可以是字符串类型或数字类型的属性.以以下对象为例:

I'm working with an object containing properties with values that are either type string or type number. Some properties are nested objects, and these nested objects also contain properties with values that could be either type string or type number. Take the following object as a simplified example:

var myObj = {
  myProp1: 'bed',
  myProp2: 10,
  myProp3: {
    myNestedProp1: 'desk',
    myNestedProp2: 20
  }
};

我希望所有这些值都是字符串类型,因此任何数字类型的值都需要转换.

I want all of these values to be type string, so any values that are type number will need to be converted.

实现这一目标最有效的方法是什么?

What is the most efficient approach to achieving this?

我尝试过使用 for..in 并尝试使用 Object.keys,但没有成功.任何见解将不胜感激.

I've tried using for..in and also played around with Object.keys, but was unsuccessful. Any insights would be greatly appreciated.

推荐答案

Object.keys 应该没问题,你只需要在找到嵌套对象时使用递归.要将某些内容转换为字符串,您只需使用此技巧

Object.keys should be fine, you just need to use recursion when you find nested objects. To cast something to string, you can simply use this trick

var str = '' + val;

var myObj = {
  myProp1: 'bed',
  myProp2: 10,
  myProp3: {
    myNestedProp1: 'desk',
    myNestedProp2: 20
  }
};

function toString(o) {
  Object.keys(o).forEach(k => {
    if (typeof o[k] === 'object') {
      return toString(o[k]);
    }
    
    o[k] = '' + o[k];
  });
  
  return o;
}

console.log(toString(myObj));

这篇关于如何将对象中的所有属性值转换为字符串类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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