Search code examples
reactjsloopsnested-loops

How to loop this array?


I'm trying to display the values of this array using map method. The data should be displayed in JSX like "local - event - age ". What is the best practice in terms of performance? I would like to avoid nested map.

const data = [
  {
    cambridge: {
      event: "birthday",
      age: "free"
    },
    boston: {
      event: "beer tasting",
      age: "only adults"
    },
    watertown: {
      event: "porch music festival",
      age: "free"
    }
  }
];

I tried something like that but it's not the format "local - event - age". Thank you!


function App() {
  return (
    <div className="App">
      {data.map(obj => (
        <div>
          <div>{Object.keys(obj).map(key => console.log(key))}</div>
          <div>{Object.values(obj).map(key => console.log(key.event, key.age))}</div>
        </div>
      ))}
    </div>
  );
}

Solution

  • You could use index from the first map to find the right array item and use the keys to access the values. Something like this:

    const childrenElements = data.map((obj, idx) => 
        Object.keys(obj).map((key) => {
          return (
            <p>
              {key} - {data[idx][key].event} - {data[idx][key].age}
            </p>
          );
        })    
      );
    
      return (
        <div className="App">
          <div>{childrenElements}</div>
        </div>
      );
    

    Here is a working example: https://codesandbox.io/s/unruffled-hugle-1eip0