【问题标题】:How to convert string value in an object to a number?如何将对象中的字符串值转换为数字?
【发布时间】:2019-06-17 21:26:17
【问题描述】:

我有一个对象,其中 user_id 的数值是字符串,但我想将它们更改为以数字形式返回,我该怎么做?

const users =
[
 { user_id: '1', name: 'Jack'},
 { user_id: '2', name: 'Emma'},
 { user_id: '3', name: 'David'}
]

// I want the output to look like this

const users =
[
 { user_id: 1, name: 'Jack'},
 { user_id: 2, name: 'Emma'},
 { user_id: 3, name: 'David'}
]

【问题讨论】:

  • 可能会以某种方式遍历用户,例如使用for 循环?你尝试过什么?
  • 你知道如何遍历数组吗?如何访问属性?如何分配到属性?如何将值转换为数字?

标签: javascript arrays string object numbers


【解决方案1】:

就地

users.forEach(u=>u.user_id*=1)

const users =
[
 { user_id: '1', name: 'Jack'},
 { user_id: '2', name: 'Emma'},
 { user_id: '3', name: 'David'}
]

users.forEach(u=>u.user_id*=1)

console.log(users);

【讨论】:

  • 我真的很喜欢这个。使用 + 作为类型强制的运算符是一个很好的技巧,但在这种情况下,它会导致代码更长而不是 *=1,并且由于 OP 没有指定功能方法,即使他声明const,使用.forEach 来操作原始对象是完全可以接受的。绝对添加到我的工具箱中。 +1
【解决方案2】:

使用简单的map,并使用一元+ 运算符转换为数字。

const users = [{
    user_id: '1',
    name: 'Jack'
  },
  {
    user_id: '2',
    name: 'Emma'
  },
  {
    user_id: '3',
    name: 'David'
  }
];

const res = users.map(({ name, user_id }) => ({ name, user_id: +user_id }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 语法:

var users = [{
    user_id: '1',
    name: 'Jack'
  },
  {
    user_id: '2',
    name: 'Emma'
  },
  {
    user_id: '3',
    name: 'David'
  }
];

var res = users.map(function(user) { 
  return { name: user.name, user_id: +user.user_id };
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

【讨论】:

    【解决方案3】:
    return users.map(user => ({...user, user_id: +user.user_id}))
    

    【讨论】:

    • 介意向 OP 解释 map 函数、展开运算符、粗箭头函数和一元加法吗?
    • @Kerndog73 介意在这里写下这条评论和-1 的每个答案吗?
    • 只是为了记录,我实际上并没有否决这个答案
    【解决方案4】:

    可能是这样的:-

    let users =
    [
     { user_id: '1', name: 'Jack'},
     { user_id: '2', name: 'Emma'},
     { user_id: '3', name: 'David'}
    ];
    
    
    users = users.map(a =>  {
      a.user_id = +a.user_id;
      return a;
    });
    console.log(users);

    【讨论】:

      【解决方案5】:

      我知道这个问题已经有了答案,但我想提供一个替代解决方案,您可能会觉得有帮助,我会解释原因。

      答案:

      您可以将Proxy 应用于每个对象并使用get 处理程序来测试属性的值是否能够强制to a number by using the + operator,而不是在users 数组上使用典型的transform。这是使用short-circuit evaluation 完成的,它返回第一个真表达式。如果一个属性的值不能转换为number,它将返回原始值而不强制(在本例中为string)。

      users = users.map(_ => 
        new Proxy(_, {get: (target, property) => +target[property] || target[property]}))
      

      为什么有用?

      代码将始终依赖于您的用例。在您的问题中,您询问了如何在您的 users 对象中将 user_id 转换为 number。如果这是一次性情况,您只需要将这个特定属性强制转换为数值,则不建议对您的对象应用代理。

      然而

      如果您发现自己有许多属性值希望尽可能转换为 number 类型,您可以考虑使用上述技术,这样您就不必精确定位和更新每个单独的转换函数中的属性名称。

      注意:由于我们使用map 方法将我们的原始对象与Proxy 处理程序捆绑在一起,您可能需要使用不同的声明(varlet ),或在您原来的 users 声明中使用 Array.from

      const users = Array.from(
      [
       { user_id: '1', name: 'Jack'},
       { user_id: '2', name: 'Emma'},
       { user_id: '3', name: 'David'}
      ], _ => new Proxy(_, {get: (target, property) => +target[property] || target[property]}));
      

      代码示例:

      let users = 
      [{
          user_id: '1',
          name: 'Jack'
        },
        {
          user_id: '2',
          name: 'Emma'
        },
        {
          user_id: '3',
          name: 'David'
        }
      ];
      
      users = users.map(_ => new Proxy(_, { get: (target, property) => +target[property] || target[property]}))
      
      users.forEach(({user_id, name}) => (console.log("user id: " + user_id + " is type: " + typeof user_id), console.log("name: " + name + " is type: " + typeof name)));

      【讨论】:

        猜你喜欢
        • 2018-07-19
        • 1970-01-01
        • 2016-03-09
        • 2021-02-03
        • 2021-08-29
        • 2019-07-07
        • 1970-01-01
        相关资源
        最近更新 更多