1

So I've got some state that is an object which looks like this

object:{
  foo: Array[3]
  bar: Array[6]
}

And The amount of entries inside the object may change, it could have 3 arrays, it could have 10. It needs to be dynamic I've got to display those as counts (in a pie chart) which accepts the data to look like this, with data being the prop inside the JSX tag

data:{[
  {x:foo, y:foo.length},
  {x:bar, y:bar.length}
]}

x outputs as the name and y outputs as the number (not a percent, the lib works it out for me)

I've tried using some examples on here such as this thread but I'm just not getting it

Preference for ES6 syntax & I'm using Victory for my graphing lib if you're interested

undefined
  • 136,817
  • 15
  • 158
  • 186
Alistair Hardy
  • 341
  • 1
  • 3
  • 12
  • 2
    I am having a hard time understanding what the question is – jk121960 Oct 04 '18 at 13:08
  • Can you edit the question and post a Minimal Complete and Verifiable example of what you have tried so far (which is causing you problems)? – lealceldeiro Oct 04 '18 at 13:08
  • The answers there should work just fine, how exactly did you try implementing them? For example `return {x:key, y:object[key].length}` should work in a map of the object keys – Patrick Evans Oct 04 '18 at 13:08

2 Answers2

5

Try following using Array.map and Object.entries

let obj = {foo : [1,2,3], bar : [1,2,3,4,5,6]};
let data = Object.entries(obj).map(([k,v]) => ({x:k, y:v.length}));
console.log(data);
Nikhil Aggarwal
  • 26,884
  • 3
  • 37
  • 53
0

You could even simply use map with keys: (to make support for ie)

const obj = {foo : [1,2,3], bar : [1,2,3,4,5,6]};
const d = Object.keys(obj).map(el => ({x:el, y:obj[el].length}));
console.log(d);
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187