0

I am working with the Wordpress REST API to retrieve some tags from a website. Maybe I haven't searched for the correctly on SO, but I am trying to get use my data and create my dataSet variable. But I am getting an error saying it's not recognizing the for loop token. I am quite new to Javascript so I don't know how to fix this.

Here is my code:

var req = new XMLHttpRequest();
var pieChart = document.getElementById('pie_chart_1');

req.open("GET", "http://example.org/wp-json/wp/v2/tags?per_page=10")
req.onload = function() {
  if (req.status >= 200 && req.status < 400) {
      var data = JSON.parse(req.responseText);
     
    } else {
      console.log("Returning an error");
    }

};

req.onerror = function() {
   console.log("Connection error");
 };

req.send();


var dataSet = [
  for(i = 0; i < data.length; i++) {
    {legendLabel: data[i].name, magnitude:data[i].count, link: "http://example.com/tag" + data[i].slug},
  }
];

  
1
  • declare i, something like for(let i = 0; ...) Commented Jul 22, 2020 at 16:46

2 Answers 2

2

You have a for loop inside the square brackets to define an array which is not syntactically correct. Since you are fetching tags using the WordPress REST API the response will be a JSON object with a tags property containing the results. It looks like you have a missing / in your link value as well.

Assuming this value for data.tags -

[{
  display_name: 'Test Name',
  slug: 'test-name',
}];

To properly use a for loop for this purpose -

const dataSet = [];
const tags = data.tags;
for (let i=0; i<tags.length; i+=1) {
  dataSet.push({
     legendLabel: tags[i].display_name, 
     link: "http://example.com/tag" + tags[i].slug,
  });
}    

A better way to create an array of JSON objects from your original array of JSON objects is to use Array.map() to "map" each element in the first array to a new element in a new array -

const dataSet = data.tags.map(function (element) {
  return { 
     legendLabel: element.display_name,
     link: "http://example.com/tag/" + element.slug,
  };
});

Taking it further, you can use an arrow function, object parameter deconstruction, explicit return, string patterns, etc for more compact syntax with the same functionality -

const dataSet = data.tags.map(({ display_name: displayName, slug }) => ({
  legendLabel: displayName,
  link: `http://example.com/tag/${slug}`,
});
Sign up to request clarification or add additional context in comments.

7 Comments

Do correct me if I am wrong, but data is using JSON.parse() so that would return a JS object. And that is different from an array, right?
@robot13 JSON.parse() can return either a JSON object or a JSON array, it depends on the input.
@robot13 there is no way to know from what you posted - it is whatever the API returns, so it could be either, but if I had to guess from the endpoint name it's either an array or an object with a property that contains an array of results.
I used the Wordpress REST API
@robot13 The likely the response is a JSON object with a property called tags that contains an array of the results. I will change my answer to reflect this. Please see - developer.wordpress.com/docs/api/1/get/read/tags
|
2

First of all, in most cases, it is better to use fetch API

In JS there is no for comprehensions so the last block of code could be refactored as follows:

const dataSet = data.map(({ name, count, slug }) => ({
  legendLabel: name,
  magnitude: count,
  link: `http://example.com/tag${slug}`
}));

1 Comment

Also, make sure that you process data inside handler function (onload)

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.