0

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

2
  • 2
    What you have provided is not valid JavaScript, therefore the question cannot be answered. Commented Oct 14, 2022 at 8:03
  • I assume this question should also have the reactjs tag, but it's not quite clear from the code given. Commented Oct 14, 2022 at 8:09

2 Answers 2

2

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.

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

1 Comment

thanks it's straigth forward enough I'd prefer 2d array method
0

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++;
}

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.