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']
        }
Paweł Baca
  • 814
  • 2
  • 15
  • 28

3 Answers3

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.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Daniel Tran
  • 6,083
  • 12
  • 25
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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
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)
Mikhail Katrin
  • 2,304
  • 1
  • 9
  • 17