get Array-Object-String thing from the given Object

后端 未结 4 1645
清歌不尽
清歌不尽 2021-01-27 03:04

I have such an Object
freq = { a: 50, r: 25, m: 25 }

I want to convert it to this Array-Object like thing

         


        
相关标签:
4条回答
  • 2021-01-27 03:37

    Try this, I think it is the most performant way to do it, because .map() is slower than simple for loop:

    let freq = { a: 50, r: 25, m: 25 } ;
    let dps = [];
    
    for (let prop in freq) {
        dps.push({
            label: prop,
            y: freq[prop]
        });
    }
    
    console.log(dps);

    0 讨论(0)
  • 2021-01-27 03:51

    Using for loop and map

    //Using for loop for object interation
    const freq = { a: 50, r: 25, m: 25 };
    var finalFreq=[];
    for(let i in freq){
      finalFreq.push({label:i,y:freq[i]});
    }
    console.log(finalFreq);
    
    //Using map and object keys
    var finalFreq=Object.keys(freq).map((freqIndex)=>{
                  return {label:freqIndex,y:freq[freqIndex]};
                  });
    console.log(finalFreq);

    0 讨论(0)
  • 2021-01-27 03:55

    You can use follow method:

    var freq = { a: 50, r: 25, m: 25 };
    /*
    dps = [  
       { label: "a",
         y: 50  },
       { label: "r",
         y: 25  },
       { label: "m",
         y: 25  }
    ];
    */
    var dps = [];
    var keys = Object.keys(freq);
    keys.map((current,index)=>{
      dps.push({label:keys[index], y:freq[keys[index]]});
    });
    console.log(dps);

    0 讨论(0)
  • 2021-01-27 04:00

    You could take the entries of the object and take a destructuring assignment for the key/value pairs and map new objects with short hand properties.

    var freq = { a: 50, r: 25, m: 25 },
        dps = Object.entries(freq).map(([label, y]) => ({ label, y }));
        
    console.log(dps);

    0 讨论(0)
提交回复
热议问题