0

I have a dynamic JSON data which changes the API could return a single object or an array of data, when the API returns a single object, I get an error on the loop and data map. But I tried not applying a forEach to data and get the data individually and store them it the data. I get an error of data.map is not a function. I have a bar graph and I want to display the data below.

 "City": {
    "Town": "Texas",
    "Number": "12"
  }

I have the code below which display the data which directs to the forEach and data.map. The code displays correctly if it returns a number of data.

  data.forEach((d) => {
       d.town = d.Town;
       d.number = +d.Number;
  }); 

  const xScale = d3.scale.ordinal()
            .domain(data.map(d => d.town))
            .rangeRoundBands([0, width], 0.1);

  const yScale = d3.scale.linear()
            .domain([0, d3.max(data, d => d.number)])
            .range([height, 0]);

How can I be able to handle dynamic data within my graph whether the API return a single or multiple values or data?

3
  • You can use Array.isArray() to test the value before trying to use .map() Commented Jul 14, 2019 at 13:25
  • @Pointy after checking with the Array.isArray(), what can i use in replace of .map() ? Commented Jul 14, 2019 at 21:50
  • If it's not an array, then it's just a single object and you can directly access data.town. Commented Jul 14, 2019 at 21:59

1 Answer 1

1

Objects, {}, in JavaScript does not have the method .map(), it's only for Arrays, [].

So in order for your code to work change data.map() to data.city.map() since City is an array which you can iterate upon.

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

2 Comments

what if the data contained only { "Town": "Texas", "Number": "12" }
you can directly return them; var data = {"Town":"Texas", "Number":"12"}; document.getElementById("demo").innerHTML = data["Town"];

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.