![](/img/trans.png)
[英]Convert an array to it to the single array and also assign key to the object values
[英]Assign key name to the value and convert to it to the single array
我有嵌套的數組格式,其中沒有名稱分配給值,格式如下所示:
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" } ]
如果要將第一個數組中的對象鍵映射為每個展平元素的屬性,請使用純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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.