0

Here are whats returned in response when hitting the service:

 {
   "2019-04-20":{
      "fare":0,
      "IsPricePos":false
   },
   "2019-04-19":{
      "fare":0,
      "IsPricePos":false
   },
   "2019-03-27":{
      "fare":45,
      "IsPricePos":true
   },
   "2019-03-26":{
      "fare":9,
      "IsPricePos":true
   },
   "2019-03-25":{
      "fare":23,
      "IsPricePos":true
   }
}

Using the below code for hitting web service and getting a response:

  fetch("/somepath/somefurtherpath/" + src + "/" + dst)
              .then(response => response.json())
              .then(result => Object.assign(newObj, result)); 

I am using fetch API as shown.

1) JSON.stringify(newObj) returns {} i.e. empty object string. 2) Not able to do JSON.parse(newObj) as it says its already an object. 3) Object.keys(newObj) returns an empty list.

The console.log(newObj) gives below (opening the object printed in console):

{}
    2019-03-21: 
        IsPricePos: true
        fare: 45
        __proto__: Object
    2019-03-22: {fare: 45, IsPricePos: true}
    2019-03-23: {fare: 45, IsPricePos: true}
    2019-03-24: {fare: 23, IsPricePos: true}

I need to access data in JSON and do operations on it. e.g. keys and its values. I need to access values of fare or IsPricePos for any given dates as keys.

I tried accessing the values as newObj."2019-03-25".fare, but did not work too.

What is the best way to do this? Does React have any specific issue with this type of situation?

I tried hardcoding an object and accessing values using JavaScript, it works well. But this situation is an issue.

Please help. Thank you.

Anas Abu Farraj
  • 1,540
  • 4
  • 23
  • 31
  • 1
    where is `newObj` defined? Where do you call `JSON.stringify(newObj)`? – Nicholas Tower Mar 21 '19 at 20:25
  • Both inside render() function itself. newObj is being define just before making the fetch api call. JSON.stringify(newObj) is just after the fetch api call. – Tushar Sharma Mar 21 '19 at 20:29
  • Please include that code in the question. – Nicholas Tower Mar 21 '19 at 20:30
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – adiga Mar 21 '19 at 20:32
  • let newObj = {}; fetch("/somepath/somefurtherpath/" + src + "/" + dst) .then(response => response.json()) .then(result => Object.assign(newObj, result)); console.log(JSON.stringify(newObj)); – Tushar Sharma Mar 21 '19 at 20:36
  • putting the code in then helped. I got the concept of json response not being avaible synchronously. Thanks a ton @NicholasTower – Tushar Sharma Mar 21 '19 at 20:48

0 Answers0