【问题标题】:How to collect values of object properties into a list?如何将对象属性的值收集到列表中?
【发布时间】:2020-11-13 21:02:08
【问题描述】:

我有这种格式的 Json 响应:

[
    {
        "date__month": 8,
        "price__sum": 999.0
    },
    {
        "date__month": 9,
        "price__sum": 999.0
    },
    {
        "date__month": 10,
        "price__sum": 888.0
    },
    {
        "date__month": 11,
        "price__sum": 777.0
    }
]

我需要将所有price__sum 收集到一个数组data = [...price__sum] 中,以便我可以使用它来创建图表。

怎么做?

【问题讨论】:

  • 你有没有尝试过?

标签: javascript reactjs ecmascript-6 chart.js


【解决方案1】:

你可以使用地图方法

var data=[
    {
        "date__month": 8,
        "price__sum": 999.0
    },
    {
        "date__month": 9,
        "price__sum": 999.0
    },
    {
        "date__month": 10,
        "price__sum": 888.0
    },
    {
        "date__month": 11,
        "price__sum": 777.0
    }
];
var mapped=data.map(i=>i.price__sum);

console.log(mapped)

【讨论】:

    【解决方案2】:

    遍历您拥有的数组并将price__sum 值推送到一个新数组中。

    let originalArray = [{
        "date__month": 8,
        "price__sum": 999.0
      },
      {
        "date__month": 9,
        "price__sum": 999.0
      },
      {
        "date__month": 10,
        "price__sum": 888.0
      },
      {
        "date__month": 11,
        "price__sum": 777.0
      }
    ]
    let newArray = [];
    
    originalArray.forEach((item)=> newArray.push(item.price__sum));
    
    console.log(newArray);

    【讨论】:

    • 如果是JSON,不需要先解析吗?
    猜你喜欢
    • 2013-02-28
    • 2020-11-16
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多