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},
}
];
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}`,
});
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}`
}));
Related
I am trying to create a method that returns a JSON object for custom headers to use with HTTPS requests. This should be defined as customHeaders={{headerKey: 'headerValue'}}
I am new to JSX and a little confused with my implementation of forEach loop here.
Here, this.props.httpHeaders passes a list of Keys and Values. The key is this.props.headerKey and corresponding value this.props.headerValue
The expected return is an Object that holds the key value pairs as {headerKey: 'headerValue'}
Here's my not so correct implementation. Can anyone explain me how to implement forEach() here? Thanks
getCustomHeaders = () => {
var customHeaders;
let keyValueStr = "";
if (this.isStatusAvailable(this.props.httpHeader) && this.isStatusAvailable(this.props.restURL)) {
// Building Custom Headers input string
this.props.httpHeader?.items?.forEach((element) => {
const attrKey = this.props.headerKey.get(element);
const attrValue = this.props.headerValue.get(element);
if (keyValueStr !== "") {
keyValueStr = keyValueStr.concat(",");
}
keyValueStr = keyValueStr+attrKey.value+": "+"'"+attrValue.value+"'";
});
}
customHeaders = JSON.parse("{" + keyValueStr + "}");
return customHeaders;
};
Hi I am trying to create JSON using below code
test(array) {
var map = {};
var tt = [];
for(var i = 0; i < array.length; i++){
var obj = array[i];
var items = obj.items;
var child = Array.prototype.map.call(items, s => s.displayName);
map[obj.displayName] = {
child
};
}
return map;
}
Expected Response:
{
RoleManagement: [
'Create',
'Edit',
'Delete',
'Change permissions'],
UserManagement: [
'Create',
'Edit',
'Delete',
'Change permissions'
]
}
Error Response
Input Image
Input Response
https://i.stack.imgur.com/tYIoR.png
I Dont need child just array of create,update,delete
Please help me out
This is the place, you have done a mistake.
map["RoleManagement"] = {
child
};
For Example,Assume creating a new property "RoleManagement" inside the map object.
Based on you expected response, you wants to create a "RoleManagement" property, that contains array['Create','Edit','Delete','Change permissions'].
Instead, you are trying to create "RoleManagement" property as an object inside the map object.
Try this
//child contains the array
map["RoleManagement"] = child;
Here,You are initializing the property with array.
It Will solve your issue.
I have our staff in a json file, and had the idea to use that data with ES6 classes. The more I work with this, the more I feel as though I may be missing something. I had this working in coffeescript as such:
fetch = require('node-fetch')
domain = 'domain.com'
apiSrc = 'api.domain.com'
slug = 'people'
class Person
constructor: (json) -> {name: #name, title: #title, school: #school, bio: #bio} = json
email: (username) ->
username.replace(/\s/, '.').toLowerCase() + '#' + domain
profile: ->
content = []
if this.name then content.push("#{#name}")
if this.title then content.push("#{#title}")
if this.school then content.push(school) for school in "#{#school}"
if this.bio then content.push("#{#bio}")
if this.name then content.push(this.email("#{#name}"))
content.join('')
fetch('http://' + apiSrc + '/' + slug + '.json')
.then((response) -> response.json())
.then((api) ->
content = []
group = []
group.push(new Person(them)) for them in api[slug]
for them, index in group
content.push(them.profile())
console.log(content.join(''))
)
But then I thought it would be even better if I could convert it to ES6. I know the use case is simple, and classes certainly aren't necessary, since I'm just using the data for templating, however, for the sake of learning, I was attempt to do this. Am I going about this the wrong way? Right now, I feel like there should be a way to return all of the "people" that I put into the Person class. However, the only way I could figure out how to do that was to run a for loop and then write it to the document.
class Person {
constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
email(username) {
return username.replace(/\s/, '.').toLowerCase() + '#' + location.hostname.replace(/[^\.\/\#]+\.[^\.\/]+$/, '');
}
profile() {
return `${this.name} ${this.title}`;
}
}
var apiSrc = 'api.domain.com';
var slug = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
.then(function(response) { return response.json() }) // .then(response => response.json())
.then(function(api) {
var content = [];
var group = [];
for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
for (var i = 0; index < group.length; i++) {
var them = group[i];
content.push(them.profile());
console.log(content.join(''));
}
});
My ES6 conversion actually isn't even working right now. API returns the JSON but after that it gets messed up. Any suggestions would be really helpful as I'm trying to better myself as a coder and hope this sort of example could help others learn Classes in a real use case.
You might try using the reviver parameter of JSON.parse. Here is a simplified example:
class Person {
// Destructure the JSON object into the parameters with defaults
constructor ({name, title, school=[]}) {
this.name = name
this.title = title
this.school = school
}
}
var api = JSON.parse(a, function (k,v) {
// Is this a new object being pushed into the top-level array?
if (Array.isArray(this) && v.name) {
return new Person(v)
}
return v
})
var group = api["people/administration"]
I'm trying to fetch an object 'single Post' within an object 'Posts' from a json file within meteor, which looks like this.
I found an effective way of doing it, using underscore findWhere to get to it. this is the code
_.findWhere(_.findWhere(CategoryCollection.find().fetch(),
{"_id":"CategoryPublication-5"}).posts,{"ID":46});
however when i put this into meteor, i'm getting undefined
this is the code i used
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
let match = _.findWhere(_.findWhere(CategoryCollection.find().fetch(), {"_id":category}).posts,{"ID": id});
console.log("match",id,category,match);
return match;
}
});
Why am i getting undefined
update.
would this be correct? i substituted the 47 id, with just id so i can use it for any link.
Im getting "category" is read-only error.
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
const category = CategoryCollection.find().fetch().find(c => c._id === id);
let post = null;
if (category) {
post = category.posts.find(p => p.ID === id);
}
console.log("post",id,category,post);
return post;
}
});
There's no need to use lodash/underscore's findWhere. This functionality is built into ES2015. Also, you may consider breaking up the code into a few lines to make it more legible.
const category = CategoryCollection.find().fetch().find(c => c._id === 'CategoryPublication-5');
let post = null;
if (category) {
post = category.posts.find(p => p.ID === 47);
}
This must be a standard Javascript problem, but my searches here did not turn up any results that were applicable to me.
I am querying a mongodb database and want to add key/values to the objects in the result array through the enrichJSON function.
The MongoBooks.find returns some documents in an Array docs. Probably enrichJSON is a bad name, it should be something like enrichArray, it is arbitrary anyway.
function enrichJSON(jsonobj) {
for (var i = 0; i < jsonobj.length; i++) {
jsonobj[i].myparam = "something meaningful";
}
return jsonobj;
}
MongoBooks.find(mongoquery, function (err, docs) {
if (err) throw err;
var step1 = docs;
var step2 = enrichJSON(step1);
console.log("step1:" + step1);
console.log("step2:" + step2);
});
The step2 console output is missing the myparam output. Same goes if I try
jsonobj[i]["myparam"] = "abctest";
in the enrichJSON.
I am getting
step1: {[{"title":"good book"}]}
step2: {[{"title":"good book"}]}
but would like to get
step2: {[{"title":"good book", "myparam":"something meaningful"}]}
Edit to give an actual (stripped down) example of my result (I edited to make it simpler but probably mixed up the brackets):
step2:{ _id: 5474e8a35e79556ced436700,
isbn10: '0370303466',
author: 'Graham Greene',
lang: 'eng',
title: 'Travels with my aunt'
}
I am still missing what I added (myparam).
You have a broken response.
{[{"title":"good book"}]}
should be something like this :
{'data' : [{"title":"good book"}]}
Then your enrich function would look like this :
function enrichJSON(jsonobj) {
for (var i = 0; i < jsonobj.data.length; i++) {
jsonobj.data[i].myparam = "something meaningful";
}
return jsonobj;
}