The front end realizes data row-to-column conversion, Key to Value (combination of Object.entries() and Map())

The requirement is that data needs to be rendered in the table

//后端返回数据格式
data:[
ML70: {
    
    jan_tss: 29, feb_tss: 28},
ML80: {
    
    jan_tss: 30, feb_tss: 29},
ML90: {
    
    jan_tss: 29, feb_tss: 28}
]
//前端想展示的数据格式
[
{
    
    division: 'ML70',jan_tss: 29, feb_tss: 28 },
{
    
    division: 'ML80',jan_tss: 30, feb_tss: 29 },
{
    
    division: 'ML90',jan_tss: 29, feb_tss: 28 }
]

The data returned by the backend of the above content: Change the Value value of a field in the front end into a Key value, and the corresponding Value value behind contains the data to be displayed. Now the Key value in the data also needs to be displayed in the corresponding table (ie ML70, ML80, ML90)

The diagram is clearer. insert image description here
Implementation ideas:
1. First change the Key of each piece of data into Value
2. Then insert the changed data into the Value of each previous piece of data ({jan_tss: 29, feb_tss: 28})

Here first use the Object.entries() method: the Object.entries() method returns an array of key-value pairs of the enumerable properties of a given object itself, and its arrangement is consistent with the order returned when using the for...in loop to traverse the object (the difference Because the for-in loop also enumerates the properties in the prototype chain)

The result returns an array (array) of key-value pairs for the given object's own enumerable properties

Demo:

const obj = {
    
     foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

Specific reference: official website

Implementation process code display:

   const data1 = Object.entries(data)  //转换为对应的数组
      console.log(data1);
/*  输出格式为数组:
    [
      0:[
        0:"ML70"
        1:{jan_tss: 29, feb_tss: 28}
      ]
      1:[
        0:"ML80"
        1:{jan_tss: 29, feb_tss: 28}
      ]
      2:[
        0:"ML90"
        1:{jan_tss: 29, feb_tss: 28}
      ]
      ]**/
   const AcctualData = data1.map((item: any) => ({
    
    
        ...item[1],                 //此处详细请见Es6扩展运算符和rest运算符的用法
        division: item[0]          //实现将转换后的每条第一笔数据(0:"ML70",0:"ML80",0:"ML90")放到后边的{jan_tss: 29, feb_tss: 28}中
      }))
      console.log(AcctualData);
     /* 输出
      [
     {division: 'ML70',jan_tss: 29, feb_tss: 28 },
     {division: 'ML80',jan_tss: 30, feb_tss: 29 },
     {division: 'ML90',jan_tss: 29, feb_tss: 28 }
     ]
     **/

Method summary:
Object.entries()
Map()
Rest operator

Guess you like

Origin blog.csdn.net/weixin_45680024/article/details/123631549