将键名称分配给值并将其转换为单个数组

时间:2019-01-07 10:08:15

标签: angular

我有嵌套的数组格式,其中没有名称分配给值,格式如下所示:

response.data: [{
  2018: [{
    December: [{
      complaintRaised: 8
      totalClosed: 0
      totalPending: 8
      totalResolved: 0
    }]
  }],
  2019: [{
    January: [{
      complaintRaised: 2
      totalClosed: 0
      totalPending: 2
      totalResolved: 0
    }]
  }]
}]

我需要将其转换为单个数组,并将键名分配给这些值。

response.data: [{
    key: "2019"
    complaintRaised: 8
    totalClosed: 0
    totalPending: 8
    totalResolved: 0
    year: "2018-December"
  },
  {
    key: "2018"
    complaintRaised: 2
    totalClosed: 0
    totalPending: 2
    totalResolved: 0
    year: "2019-January"
  }
]

1 个答案:

答案 0 :(得分:1)

如果要将第一个数组中的对象键映射为每个扁平化元素的属性,请使用纯JavaScript来使用下面的代码。

请告诉我是否可以解决您的问题。

const x = [{
  2018: [{
    December: [{
      complaintRaised: 8,
      totalClosed: 0,
      totalPending: 8,
      totalResolved: 0
    }]
  }],
  2019: [{
    January: [{
      complaintRaised: 2,
      totalClosed: 0,
      totalPending: 2,
      totalResolved: 0
    }]
  }]
}];

const result = Object.entries(x[0]).map((e) => {
 return Object.assign(
        {}, 
        Object.values(e[1][0])[0][0], 
        { key: e[0], year: e[0] + '-' + Object.keys(e[1][0])[0] }
    );
})


console.log(result);