简体   繁体   English

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

[英]Assign key name to the value and convert to it to the single array

I have nested Array Format in which there is no name assigned to the values, the format is shown below: 我有嵌套的数组格式,其中没有名称分配给值,格式如下所示:

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

which I need to convert it into a single array with key names assign to the values. 我需要将其转换为单个数组,并将键名分配给值。

 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" } ] 

If you want to map the object key from the first array as a property of each flattened element, using pure javascript the code below may work for you. 如果要将第一个数组中的对象键映射为每个展平元素的属性,请使用纯JavaScript,以下代码可能适用。

Please, tell me if it solves your problem. 请告诉我是否可以解决您的问题。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM