转换具有不同数据类型的数组 [英] Converting array with Different data type

查看:72
本文介绍了转换具有不同数据类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Javascript中转换它:

How to convert this in Javascript from:

[
   {
      "label": "Purok I",
      "y": "1"
   },
   {
      "label": "Purok II",
      "y": "1"
   },
   {
      "label": "Purok III",
      "y": "2"
   }
]

to:

[
   {
      label: "Purok I",
      y: 1
   },
   {
      label: "Purok II",
      y: 1
   },
   {
      label: "Purok III",
      y: 2
   }
]

任何帮助?

推荐答案

此方法将更新对象中的所有数字类型自动。

This method will update all numeric types in your objects automatically.

let arr = [{
    "label": "Purok I",
    "y": "1"
  },
  {
    "label": "Purok II",
    "y": "1"
  },
  {
    "label": "Purok III",
    "y": "2",
    "example": "432.23"
  }
];

// Map over your array of objects
arr = arr.map(obj => {
  // Map over all the keys in your object
  Object.keys(obj).map(key => {
    // Check if the key is numeric
    if (!isNaN(obj[key])) {
      obj[key] = +obj[key];
    }
  })
  return obj;
});
console.log(arr);

这篇关于转换具有不同数据类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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