如何遍历包含子对象的对象列表并创建另一个自定义对象?

时间:2020-04-13 07:11:55

标签: javascript json

我有一个这样的对象列表,我从一个api处获得了此响应:

  {
        "1/22/20": {
            "new_daily_deaths": 0,
            "total_cases": 1,
        },
        "1/23/20": {
            "new_deaths": 0,
            "total_cases": 10,
        },
        "1/24/20": {
            "new_deaths": 0,
            "total_cases": 20
        }
  }

预期输出:

{
   x:1/22/20,1/23/20,1/24/20 // key of every object
   y:1,10,20 //total_cases
 }

请帮助我如何实现这一目标。我尝试了object.stringify,但没有给我预期的结果。

1 个答案:

答案 0 :(得分:1)

您可以使用Object.keys()Object.entries()方法,例如:

const data = {
        "1/22/20": {
            "new_daily_deaths": 0,
            "total_cases": 1,
        },
        "1/23/20": {
            "new_deaths": 0,
            "total_cases": 10,
        },
        "1/24/20": {
            "new_deaths": 0,
            "total_cases": 20
        }
  }

const keys = Object.keys(data).join(',')
const cases = Object.entries(data).map(([k,v]) => v).map(x=>x.total_cases).join(',')
const result = { x: keys, y: cases}
console.log(result)


输出为{x:1/22/20,y:1},{x:1/23/20,y:10}

const data = {
        "1/22/20": {
            "new_daily_deaths": 0,
            "total_cases": 1,
        },
        "1/23/20": {
            "new_deaths": 0,
            "total_cases": 10,
        },
        "1/24/20": {
            "new_deaths": 0,
            "total_cases": 20
        }
  }

const result = Object.entries(data).map(([k,v]) => ({x: k, y: v.total_cases}))
console.log(result)