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

3
  • 2
    I am having a hard time understanding what the question is Commented Oct 4, 2018 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)? Commented Oct 4, 2018 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 Commented Oct 4, 2018 at 13:08

2 Answers 2

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

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

1 Comment

@AlistairHardy - Glad to help you!
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);

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.