converting to key, values pair - javascript

My question
How to read rom txt file in JS
Best approach to process the data. Something like this below or ????
var data = [
{
name: "Orange",
type: "Fruit",
desc: "some description about the recipe"
},
{
name: "Spinach",
type: "Veg",
desc: "some description about the recipe"
},
{
name: "Beans",
type: "Veg",
desc: "some description about the recipe"
},
]
I want to have an object array so that I can process it further to print out unique names of fruits, just veggies and just fruits.

You can accomplish this using AJAX and then a regular expression.
If you're using jQuery:
$.ajax({
url: 'someTextFile.txt',
success: function(data) {
var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g,
recipe, allRecipies = [];
while (recipe = rege.exec(data)) {
allRecipies.push({
name: recipe[1],
type: recipe[2],
desc: recipe[3],
});
}
console.log(allRecipies);
}
});
If you're not using jQuery
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = xhttp.responseText;
var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n \t]*([a-zA-Z0-9 \.]+)/g,
recipe, allRecipies = [];
while (recipe = rege.exec(data)) {
allRecipies.push({
name: recipe[1],
type: recipe[2],
desc: recipe[3],
});
}
console.log(allRecipies);
}
};
xhttp.open("GET", "filename", true);
xhttp.send();

Don't bother creating your own parser to read in formats.
Save your content in a standard data-interchange format like json or xml
There are so many others and lookup standard libraries to parse them and get your information.
I'll recommend json, as Javascript as a JSON object for parsing JSON Files. And their are other good libraries for parsing JSON.

Related

Issue formatting data in JavaScript for a pie chart

I am not a JavaScript expert and I am trying to put a simple pie chart together using the data from a csv file. The sample code for the pie chart with its input data looks like below and it works perfectly.
var pie = new d3pie("pie", {
header: {
title: {
text: "A Very Simple Pie",
fontSize: 30
}
},
data: {
content: [
{ label: "JavaScript", value: 264131 },
{ label: "Ruby", value: 218812 },
{ label: "Java", value: 157618}
]
}
});
but when I try to use the data from the csv file. It says no data is provided. I obviously try to pass the dynamic data to the data.content but it seems like I am not doing it correctly. Below is my code:
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
Any idea what I am doing wrong here?
As noted in my comment, your problem is because d3.csv acts asynchronously, and input_data isn't populated when d3pie tries to create your chart.
There is something highly suspicious going on with input_data in the other examples -- it should be called for every item in data, but seems only to be called once. Rather than using input_data to collate intermediate results, it's much easier to use javascript's map function to transform your csv data into the format you want:
d3.csv("data.csv", function (data) {
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: data.map( function(d){
return { label: d['First'], value: +d['Age'] }
})
}
});
});
map iterates over an array and produces an array as output, so it's much cleaner and easier than creating extra arrays on to which you push data, etc.
You probably want to put your d3pie code inside your callback function because you want to call it after the data returns (see this example):
var input_data = []
d3.csv("data.csv", function (data) {
input_data.push({
label: data["First"],
value: +data["Age"]
});
console.log(input_data); // This shows [{label: "james", value:30},{"John",value:22}]
var pie = new d3pie("pie", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});
const promise = d3.csv("data.csv", function (data) {
input_data.push({
'label': data["First"],
'value': +data["Age"]
});
});
promise.then(function(){
var pie = new d3pie("pieChart", {
header: {
title: {
text: "Simple Pie",
fontSize: 30
}
},
data: {
content: input_data
}
});
});

ArcGIS API for Javascript: FeatureLayerCollection doesn't displaye all the features

This image shows the result of my implementation.
The problem here is the feaure layer displayed in the map shows only one of the features passed in the code.
How have I done it?
Create a feature layer using new FeatureLayer(featureCollectionObject, options?).
Create a Query and QueryTask to request features from the arcgi server.
var selectQuery: Query = new Query();
selectQuery.returnGeometry = true;
selectQuery.where = "1=1";
selectQuery.outFields = ["NAME", "X", "Y"];
var queryTask_XZQH = new QueryTask(FL_XZQH_URL);
queryTask_XZQH.execute(selectQuery);
Define a event handler for "complete" of queryTask.
function onQueryTask_XZQHComplete(evt: object) {
console.log(evt.featureSet.geometryType);
//console.log(evt.featureSet);
FL_XZQH = new FeatureLayer({
featureSet: evt.featureSet,
layerDefinition: {
geometryType: "esriGeometryPolygon",
className: "xzqh",
objectIdField:"OBJECTID",
fields: [
{
name: "OBJECTID ",
type:"esriFieldTypeOID",
alias:"OBJECTID"
},
{
name: "ID ",
type:"esriFieldTypeInteger ",
alias:"Id"
},
{
name: "Name",
type: "esriFieldTypeString",
length: 50,
alias: "行政区划名称"
},
{
name: "X",
type: "esriFieldTypeDouble",
alias: "经度"
},
{
name: "Y",
type: "esriFieldTypeDouble",
alias: "纬度"
}
]
}
});
map.addLayer(FL_XZQH);
}
The result of QueryTask is fine, and the count of the features is 18.
However, when I use map.addLayer, the map just displays one feature.
The feature layer does not have a valid object ID. Make two changes to fix it:
Change this:
selectQuery.outFields = ["NAME", "X", "Y"];
To this (i.e. include the object ID in your query):
selectQuery.outFields = ["OBJECTID", "NAME", "X", "Y"];
Change this:
{
name: "OBJECTID ",
type:"esriFieldTypeOID",
alias:"OBJECTID"
},
To this (i.e. remove the space at the end of the field name):
{
name: "OBJECTID",
type:"esriFieldTypeOID",
alias:"OBJECTID"
},
Note: this will only work if the feature service actually has a field called OBJECTID.

Javascript HTTP POST input JSON error

I am trying to add JSON request into a HTTP POST javascript code like below. Please see the code below.
My problem is, I need to input following format JSON and send it. But, I am getting Uncaught SyntaxError: Unexpected token : Could you please advise, What is wrong formatting JSON in my code below?
Sample JSON format to be sent=> {"records":[{"value":{"foo":"bar"}}]}
Code:
function savedata() {
var membernameStr = parseInt(document.getElementById("MemberID").value).toString();
var data = JSON.stringify({
"records": [["value":{"MemberID":membernameStr,"MemberName":"Anna", "AccountNo":"7623", "Address":"Peter", "AccountType":"Peter"}]]
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.status == 200) {
console.log(this.responseText);
// Based on successful response, call next POST API.
var xhr1 = new XMLHttpRequest();
xhr1.open("POST", "http://localhost:3500");
xhr1.send(data);
}
});
xhr.open("POST", "http://localhost:8082/topics/topictest");
xhr.setRequestHeader("Content-Type", "application/vnd.kafka.json.v2+json; charset=utf-8");
xhr.setRequestHeader("Accept", "application/vnd.kafka.v2+json; charset=utf-8");
xhr.send(data);
}
Your JSON was incorrect in the syntax, please have a look at below JSON:
{
"records": [
[
{
"value": {
"MemberID": membernameStr ,
"MemberName": "Anna",
"AccountNo": "7623",
"Address": "Peter",
"AccountType": "Peter"
}
}
]
]
}
why did you use array within array ? you can also use as below ..
{
"records": [
{
"value": {
"MemberID": membernameStr ,
"MemberName": "Anna",
"AccountNo": "7623",
"Address": "Peter",
"AccountType": "Peter"
}
}
]
}

Highcharts not draw with JSON format

the problem is that the chart doesn't draw anything when the JSON response is obtained, the code is below:
var opciones = {
chart: {
type: 'bar',
renderTo: 'charterContainer'
},
series: []
};
var json;
$.get( "graficas.php?query="+data+"&rutas="+seleccion_rutas+"&residuos="+seleccion_residuos+"", function( tabla_conteo ) {
console.log(tabla_conteo);
json = jQuery.parseJSON(tabla_conteo);
var newSeriesData = {
name: json['1'].name,
data: json['1'].data
};
opciones.series.push(newSeriesData);
});
var chart = new Highcharts.Chart(opciones);
And the JSON response is:
{"1": { "name": "Jesus Emilio Ramirez ", "data":[ 111,127,308,262,0]},"2": { "name": "Bioterio ", "data":[ 0,391,0,359,284]}}
But if the data is introduced manually into the 'opciones' variable, the chart draws, so I believe that is a problem with the push or format.
Put chart creation inside your $.get() callback:
$.get( "graficas.php?query="+data+"&rutas="+seleccion_rutas+"&residuos="+seleccion_residuos+"", function( tabla_conteo ) {
console.log(tabla_conteo);
json = jQuery.parseJSON(tabla_conteo);
var newSeriesData = {
name: json['1'].name,
data: json['1'].data
};
opciones.series.push(newSeriesData);
var chart = new Highcharts.Chart(opciones);
});

How do I build a javascript array from an ajax call that returns a json array?

I am making an ajax call that returns some json data. I need to take this data, loop through it and build a new javascript array.
This is what the returned json looks like:
{
query: [ ],
products: 
[

{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link1.php"
},

{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link2.php"
},

{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link3.php"
}
]
}
How do I loop through this data in javascript? This is what I have so far but it is very wrong! - apologies my javascript is not my strongest skill!
var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {
var arrProducts = [
for (var product in allProducts) {
title = product.title,
url = product.url,
label = product.title,
magazine = product.magazine,
image = product.imageThumb,
newsstand = product.newsstand,
googleplay = product.googleplay,
kindle = product.kindle,
barnesnoble = product.barnesnoble,
zinio = product.zinio,
kobo = product.kobo,
waterstones = product.waterstones,
type = product.type,
brandurl = product.brandurl
},
];
});
console.log(arrProducts);
Assuming the JSON is served with the correct Content-Type (application/json), jQuery will automatically parse the JSON and populate the first argument of the callback function with the result.
var arrProducts = data.products;
http://api.jquery.com/jQuery.parseJSON/
jQuery.parseJSON("json string")
Using jQuery's getJSON
http://api.jquery.com/jQuery.getJSON/
$.getJSON(url, function(data){
// Your code goes here
});

Categories