1

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
  • What have you tried so far? Commented Oct 2, 2018 at 11:38

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

using map() is even better. I was using simple for loop. Thanks for the quick response.
I was using simple for loop - well, your loop would be 150ns quicker for each iteration :D if you had code, why not put it in the question?
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);

Comments

0

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

1 Comment

Why would you push in a map and not return anything from map, and discard the mapped result? ... you may as well use forEach
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.