【问题标题】:JSON values convert to percentageJSON 值转换为百分比
【发布时间】:2019-11-25 00:08:11
【问题描述】:

使用打字稿,将 JSON 值转换为百分比的最佳方法是什么?

JSON

{
  "outer_attribute": {
    "brands": [
    {
        "brand_names": "brand6",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.03935382863419896"
    },
    {
        "brand_names": "brand5",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.00935382863419896"
    },
    {
        "brand_names": "brand12",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.30935382863419896"
    }
    ]
}
}

我需要将“customer_visit_ratio”的值转换为百分比值。尝试了 .map 但没有用。

【问题讨论】:

  • 可以工作..您尝试了什么?请注意,这些是字符串..您需要先转换为浮点数..
  • @Abhijeetc50 在下面查看我的更新答案

标签: json angular typescript


【解决方案1】:

你可以像这样使用.map

var passengers = {
  "outer_attribute": {
    "brands": [
    {
        "brand_names": "brand6",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.03935382863419896"
    },
    {
        "brand_names": "brand5",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.00935382863419896"
    },
    {
        "brand_names": "brand12",
        "Vertical": "Automotive",
        "customer_visit_ratio": "0.30935382863419896"
    }
    ]
}
};


var modifiedBrands = passengers.outer_attribute.brands.map(function(arrayCell){
  return {...arrayCell, customer_visit_ratio: (arrayCell.customer_visit_ratio* 100).toFixed(2)};
});
passengers.outer_attribute.brands = modifiedBrands ;
console.log('passengers', passengers);

【讨论】:

    【解决方案2】:

    试试这样:

    this.data.outer_attribute.brands = this.data.outer_attribute.brands.map(
      item => ({...item, percent : (Number(item.customer_visit_ratio) * 100).toFixed(2)})
    ); 
    

    Working Demo

    【讨论】:

    • 谢谢。它工作正常,但它添加了一个新的 JSON 键值对。
    • 这个也可以不用添加新密钥,查看修改后的demo
    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2019-07-03
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多