sam
sam

Reputation: 956

How to print array key and value using map function

I'm trying to print the key and value of an array but i can't get it done, what's the best way to do this? but i'd like to use map but any other better method is also ok, I'd also like to be able to track the index of the array.

colorArray = [0:0: 'Red', 0:1: 'Blue', 0:2: 'Green', 0:3: 'Orange']
{colorArray.map((val, index) => {
     <div> 
       <div className='value-img' >
         <span>(index+1)"."+val+", "key+", "index<span>
       </div>
    </div>

}

and I want the result below

  1. Red, 0:0, 0
  2. Blue, 0:1, 1
  3. Green, 0:2, 2
  4. Orange, 0:3, 3

How can I achieve this result above. Thanks

Upvotes: 0

Views: 63

Answers (2)

Anu
Anu

Reputation: 389

First of all the array is not syntactically correct. if you wish to maintain the same key-value pair for some reason, it cannot be done with array, you can go for Object

    var colorObj = {['0:0']: 'Red', ['0:1']: 'Blue', ['0:2']: 'Green', ['0:3']: 'Orange'}
    Object.entries(colorObj).map((c)=>console.log(c[0],c[1]))

Or better a 2D array.

     var colorArray = [['0:0', 'Red'],['0:1', 'Blue'],['0:2', 'Green'],['0:3', 'Orange']]
    colorArray.map((c)=>console.log(c[0],c[1]))

Hope this helps.

Upvotes: 2

tarkh
tarkh

Reputation: 2549

For this task you can use Object, instead of Array, so it will utilize key -> value pairs. Check inline comments:

// You can use Object instead
// Here we define key -> value pairs
const colorObject = {
  "0:0": "Red",
  "0:1": "Blue",
  "0:2": "Green",
  "0:3": "Orange"
}

// Counter to count iterations
let counter = 0;

// Iterate Object with for loop
// and increase counter each iteration
for(const el in colorObject) {
  // Form your html as you need
  // For now we will just print it to console
  console.log(`
  <div> 
    <div className='value-img' >
      <span>${counter+1} ${colorObject[el]}, ${el}, ${counter}<span>
    </div>
  </div>
  `);
  // Increase counter
  counter++;
}

Upvotes: 0

Related Questions