1

I have a JSON coming as a response and I need to map over it using React. The JSON itself is an array and it also contains an array and I need to map over all the objects and somehow know the variable names.

This is my JSON. Is there a way to do that?

[
   {
      "name":{
         "english":"name1",
         "finnish":" name2"
      },
      "imageList":[
         "xyxyxyxy"
      ]
   }
]

So i have tried mapping over it using this:

{this.state.imageData.map((item, key) =>
    <p>Device name: {item.name}, En device name: {item.name.english}</p>
)}

But I get the error that it doesnt know what "english" is:

Objects are not valid as a React child (found: object with keys {english, finnish}). If you meant to render a collection of children, use an array instead.

I get the JSON as a response from fetch:

let images = await fetch(`myurl` + id);
return await images.json();

What I need is to be able to map over each object in the list and then also map over data in the imageList.

So like in the example above I would like to do something like:

this.state.imageData.map((item, key) =>
    <p>Device name: {item.name}, En device name: {item.name.english}</p>
    for(image: item.imageList){
            console.log(image)
        }
12
  • 1
    What have you tried so far? You can map over your array and then for every item use Object.keys to get the value of keys of object. Commented May 6, 2020 at 10:51
  • 1
    It is unclear, how exactly you want this data to be rendered. Commented May 6, 2020 at 10:52
  • 1
    What exactly were you trying to print {item.name} with this? Commented May 6, 2020 at 11:15
  • 1
    Try removing {item.name} and see if {item.name.english} prints? Commented May 6, 2020 at 11:18
  • 1
    Let us continue this discussion in chat. Commented May 6, 2020 at 11:21

1 Answer 1

2

The error says it -

Objects are not valid as a React child (found: object with keys {english, finnish}). If you meant to render a collection of children, use an array instead.

You are trying to render {item.name} which is an object. If you want to render the object in object structure then do this -

{this.state.imageData.map((item, key) =>
    <p>Device name: {JSON.stringify(item.name)}, En device name: {item.name.english}</p>
)}

To render the array imageList inside your json , you can do it -

{this.state.imageData.map((item, key) =>
    <div>
       <p>Device name: {JSON.stringify(item.name)}, En device name: {item.name.english}</p>
       {item.imageList.map((image, key) => <p>.....</p> )} //what you want to render
    </div>
)}
Sign up to request clarification or add additional context in comments.

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.