robot13
robot13

Reputation: 71

Creating a JS object

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},
  }
];

  

Upvotes: 0

Views: 49

Answers (2)

doublesharp
doublesharp

Reputation: 27599

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}`,
});

Upvotes: 3

Alexander Alexandrov
Alexander Alexandrov

Reputation: 1362

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}`
}));

Upvotes: 2

Related Questions