1

I have a data structure as below:

{
  oldPics: {
    [title: 'dog', url: 'www.dog.com'],
    [title: 'cat', url: 'www.cat.com'],
    [title: 'bird', url: 'www.bird.com'],
  },

  newPics: {
    [title: 'fox', url: 'www.fox.com'],
    [title: 'lion', url: 'www.lion.com'],
  },

  archivedPics: {
    [title: 'eagle', url: 'www.eagle.com'],
    [title: 'fish', url: 'www.fish.com'],
    [title: 'monkey', url: 'www.monkey.com'],
  },
}

I want to display the data like this:

<div>
  <div>
    <h3>old</h3>
    <p>title: dog, url: www.dog.com</p>
    <p>title: cat, url: www.cat.com</p>
    <p>title: bird, url: www.bird.com</p>
  </div>


  <div>
    <h3>new</h3>
    <p>title: fox, url: www.fox.com</p>
    <p>title: lion, url: www.lion.com</p>
  </div>

  <div>
    <h3>archived</h3>
    <p>title: eagle, url: www.eagle.com</p>
    <p>title: fish, url: www.fish.com</p>
    <p>title: monkey, url: www.monkey.com</p>
  </div>
</div>

I have tried in my component to render it as below but it renders empty <div> elements:

  _renderPics(group) {

    const content = []

    const piccies = Object
                    .keys(group)
                    .map(key => content.push(
                        <div key={key}>title: {group[key].title} url: {group[key].url}</div>
                    ));
    return content

  }

Any idea?

1
  • it renders empty html elements Commented Mar 12, 2018 at 15:33

2 Answers 2

2

Assuming that your data structure is correct in your real case, two nested maps should do the job:

_renderPics(group) {
  return Object
    .keys(group)
    .map((key, index) => (
      <div key={index}>
        <h3>{key.replace('Pics', '')}</h3>
        {group[key].map((pic, i) => (
          <div key={i}>title: {pic.title}, url: {pic.url}</div>
        ))}
      </div>
    ));
}

Demo: https://codesandbox.io/s/l94mml0yj9

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

Comments

1

You must correct your data structure from

oldPics: {
 [title: 'dog', url: 'www.dog.com'],
 [title: 'cat', url: 'www.cat.com'],
 [title: 'bird', url: 'www.bird.com'],
}

To

oldPics: [
 {title: 'dog', url: 'www.dog.com'},
 {title: 'cat', url: 'www.cat.com'},
 {title: 'bird', url: 'www.bird.com'},
]

then

{Object.keys(group).map((key, y) =>
  <div key={y}>
    <h3>{key.replace('Pics', '')}</h3>
      {group[key].map((item, y) =>
      <div key={y}>title: {item.title} url: {item.url}</div>
      )}
  </div>
)}

https://codesandbox.io/s/1r3mp5jnj4

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.