get Array-Object-String thing from the given Object

こ雲淡風輕ζ 提交于 2021-02-05 09:18:07

问题


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

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

dps = [  
   { label: "a",
     y: 50  },
   { label: "r",
     y: 25  },
   { label: "m",
     y: 25  }
];

This is for creating a Chart with canvas.


回答1:


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);



回答2:


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);



回答3:


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);



回答4:


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);


来源:https://stackoverflow.com/questions/52607584/get-array-object-string-thing-from-the-given-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!