I have such an Object
freq = { a: 50, r: 25, m: 25 }
I want to convert it to this Array-Object like thing
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);
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);
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);
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);