0

This is my object and I want to map this in my component but I have problem, I cant use map on this object. First value is vote and next is array of users. How I cna use map on this in babel ?

  var ObjVote = {
        '1':['EwaK','Jacek','Jacek'],
        '2':['Anna','Pawel','EwaK'],
        '3':['Anna','EwaK','Jacek'],
        '4':['Jas','Jas','Pawel'],
        '5':['Anna','Jas','Pawel']
        }
1

3 Answers 3

2

You can use:

Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote {...data} key={data.vote} />)

Or

Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote data={data} key={data.vote} />)

Now inside Vote component you can access votes by props.data.votes and voters array by props.data.voters.

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

7 Comments

Unexpected token, expected ; voters: ObjVote[vote]}, after voters
@PawełBaca put the braces around {} in first map, like this: ({ vote: vote, voters: ObjVote[vote]}), it will work.
Object.keys(ObjVote) .map(vote => ({ vote: vote, voters: ObjVote[vote]})) .map(data => <Vote ...data key={data.vote} />) now error after vote:
@PawełBaca put the {}, like this: <Vote {...data} key={data.vote} /> or <Vote vote={data.vote} voters={data.voters} key={data.vote} />
Ok it work,but I have to style each element of data.voters. Do you know how ? :) data.voters is EwaKJacekJacek I need <div>Ewa</div> <div>Jacek</div>
|
0

You cannot use map on Object. But you can use Object.keys() and then map.

 let ObjVote = {
  '1':['EwaK','Jacek','Jacek'],
  '2':['Anna','Pawel','EwaK'],
  '3':['Anna','EwaK','Jacek'],
  '4':['Jas','Jas','Pawel'],
  '5':['Anna','Jas','Pawel']
}

let data = Object.keys(ObjVote).map(key => {
  return {
    vote: key,
    users: ObjVote[key]
  }
})

console.log(data)

1 Comment

Why Pawel and Ewak
0

You can convert it to an array using Array#from, and then you can map it. First you need to convert the object to an array like object, by adding the length property. To add the length property, you can use Object#assign, and Object#keys:

const ObjVote = {
  '1':['EwaK','Jacek','Jacek'],
  '2':['Anna','Pawel','EwaK'],
  '3':['Anna','EwaK','Jacek'],
  '4':['Jas','Jas','Pawel'],
  '5':['Anna','Jas','Pawel']
}

const array = Array.from(
  Object.assign( 
    {}, 
    ObjVote, 
    { length: Object.keys(ObjVote).length + 1 } // add the number of keys + 1 (the missing 0 index) as the length property 
  ),
  (voters, vote) => ({ vote, voters }) // create the vote object
).slice(1); // remove the 1st empty element

console.log(array);

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.