2

I am currently fetching a json Object from the following sample URL: https://demo0046512.mockable.io/stream/anycontent

My purpose is to iterate trough each array ("zone") and make a switch-case which will call different methods depending on the type fields

I tried looking at this other similar case Iterating over JSON in React but I am still struggling with iterating trough the json Object correctly, what am I not doing properly?

Here's the iteration code:

interpretJson(jsonObj){

    if(jsonObj){    
      var arr = [];
      Object.keys(jsonObj).map((zone, index) => {
          arr.push(jsonObj[zone]);
          }) 
      return(
        <div>
        <p> interpretJson output: </p>
          <ul>
            {arr.map(item => {
                item.type
              }) 
            }
          </ul>
        </div>  
      )
    }
  }

Displaying the output is only meant to see if it is being iterated correctly, so I can proceed to the switch case, but apparently something is not right.

2
  • because you are not returning anything inside map body use this: {arr.map(item => <li>item.type</li> )} Commented Mar 17, 2018 at 15:41
  • tried that and <li>{item.type}</li> but it is still not printing the types... Commented Mar 17, 2018 at 15:44

1 Answer 1

2

You need to loop over the zones object keys and then into the zone1 and zone2 array to collect the diffrent types and after that remove the duplicates.

var jsonObj = {
    "zones":{    
        "zone1":[
            {"type": "text", "url": "http://pastebin.com/raw/1U5vhVzH", "displaytime": "15"},      
            {"type": "image", "url": "http://i.imgur.com/FuD18KJ.jpg", "displaytime": "10"},
            {"type": "video", "url": "http://techslides.com/demos/sample-videos/small.mp4" }
        ],
        "zone2":[
            {"type": "text", "url": "http://pastebin.com/raw/1U5vhVzH", "displaytime": "16"},      
            {"type": "image", "url": "http://i.imgur.com/FuD18KJ.jpg", "displaytime": "11"},
            {"type": "video", "url": "http://techslides.com/demos/sample-videos/small.mp4" }
        ]
    }
}

      var arr = [];
      Object.keys(jsonObj.zones).forEach((zone, index) => {
              jsonObj.zones[zone].forEach((obj, idx) => {
                  arr.push(obj.type)
              })
          })
          
     arr = arr.filter((x, i, a) => a.indexOf(x) == i) // remove duplicate entries
console.log(arr);

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

2 Comments

That's completely correct sir. So my problem was that I was passing a group of inner objects at a time with jsonObj[zone] instead of one by one?
Glad it helped you

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.