Skip to content
Advertisement

How can I use the next array element from a map function?

I have a JSON file with 20k entries in it. The even number indexes are all ID numbers. The element right after each ID number is the matching string for that ID that I need to put in to a table.

ID Matching Str ID Matching Str
1 String for 1 3 String for 3
2 String for 2 4 String for 4

Here’s the JSON import (and conversion):

    //get the json data
    const jsonData = require("../Reference Files/Json Files/randomEffects.json");

    //convert data in to an array
    const objInnerValues = Object.values(jsonData.effects)

And here’s the code I currently have:

                {objInnerValues.map((thing, Index) => (

                    // Ternary operator to only create rows from even indexes (0, 2, 4, 6 etc)
                    (Index % 2 === 0 ? 
                        <>
                            {/* Thing, in this true instance, is the id number */}
                                <SuperTH>{thing}</SuperTH>
                            {/* need to get the next 'thing' here */}
                                <SuperTD NoHoverTD>{thing+1}</SuperTD>
                        </>
                        :
                        <>
                            {console.log("No ID element here")}
                        </>
                    )

                ))
                }

The problem here is I need to access the very next element of whatever index has been mapped through. I can’t use thing[1] because that breaks down whatever string is provided and returns the second character (if there is one). Tried using thing+1 but that just added “1” to the end of whatever string came out. Not sure how to get to the next element in the same cycle of the map function

Advertisement

Answer

Assuming your JSON structure looks like

[
  '1',
  'item for id - 1',
  '2',
  'item for id - 2',
  '3',
  'item for id - 3',
  '4',
  'item for id - 4',
];

You could first process this object to make it simpler to iterate over it. Use Array.prototype.reduce to convert it into structure such as

[
  { id: '1', text: 'item for id - 1' },
  { id: '2', text: 'item for id - 2' },
  { id: '3', text: 'item for id - 3' },
  { id: '4', text: 'item for id - 4' }
]

So your code would look like

const jsonObj = [
  '1',
  'item for id - 1',
  '2',
  'item for id - 2',
  '3',
  'item for id - 3',
  '4',
  'item for id - 4',
];


const objInnerValues = jsonObj.reduce((acc, cur, index, original) => {
  if(index % 2 === 0) {
    const item = {
      id: cur,
      text: original[index+1]
    };
    acc.push(item);
  }
  return acc;
}, []);

{
  objInnerValues.map((thing) => (
    <>
      <SuperTH>{thing.id}</SuperTH>
      <SuperTD NoHoverTD>{thing.text}</SuperTD>
    </>
  )
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement