0

I have data stored in an object and I want to loop through the data and set it as the props for my component.

My component is a card, and I want to show a card for every piece of data in the loop.

This is code so far -

function App() {
  let title = [];
  for (let key in projectDataObject) {
    let newObj = projectDataObject[key].sites;
    for (let key in newObj) {
      title = newObj[key].title;
    }
    return (
      <div className="App">
        <header className="App-header">
          <Card title={title}></Card>
        </header>
      </div>
    );
  }
}
export default App;

The problem here is because of the "return" it stops the loop at the first item, and does not loop through everything else.

How can I do this?

2 Answers 2

1

use it like this:

<div className="App">
  <header className="App-header">
  {Object.keys(yourObject).map(function(key) {
    return <Card title={yourObject[key].title} />;
  })}
 </header>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

This code doesn't make any sense. You're just taking the last one as the title, so looping is pointless.

for (let key in newObj) {
    title = newObj[key].title;
} 

Since I can't really tell what you're trying to do there, I'll make an assumption to get you pretty close. It looks like you're trying to pull out all of the titles from your object graph, so let's do that first.

   function App() {
        const titles = /* I can't tell what your data structure is, 
            so flatten it to get all of the titles out and into an array here */

        return (
          <div className="App">
            <header className="App-header">
              {/* this will put a list of cards in the header */}
              {titles.map(title => <Card title={title}/>)}
            </header>
          </div>
        );
      }
    }
    export default App;

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.