转换具有不同数据类型的数组

时间:2019-03-02 03:05:12

标签: javascript arrays json object ecmascript-6

如何在Javascript中将其转换为:

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

收件人:

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

有帮助吗?

3 个答案:

答案 0 :(得分:3)

使用map将所有字​​符串化的数字转换为非字符串化的数字,并进行如下分解:

const data = [
   {
      "label": "Purok I",
      "y": "1"
   },
   {
      "label": "Purok II",
      "y": "1"
   },
   {
      "label": "Purok III",
      "y": "2"
   }
];

const numbered = data.map(({ label, y }) => { return {label, y: parseInt(y)}});

console.log(numbered);
.as-console-wrapper { max-height: 100% !important; top: auto; }

编辑

原来不可能制作无字符串的属性名称:

var obj = {
  foo: "bar",
  one: 1
};

console.log(obj);

答案 1 :(得分:3)

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

let result = p.map(function(x) { 
    x.y = Number(x.y);  
    return x;
});

console.log(result);

答案 2 :(得分:2)

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

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);