簡體   English   中英

轉換不同數據類型的數組

[英]Converting array with Different data type

如何在 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
   }
]

有什么幫助嗎?

此方法將自動更新對象中的所有數字類型。

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

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

 let p = [ { "label": "Purok I", "y": "1" }, { "label": "Purok II", "y": "1" }, { "label": "Purok III", "y": "2" } ] let result = p.map(function(x) { xy = Number(xy); return x; }); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM