Parse json and give to category in Highcharts - json

I am using Highcharts and want to parse JSON and assign to categories part.
This is my chart data:
var chartData = {
"chart" :[
{name: "kolkata",categories: ["male", "female"]},
{name: "Mumbai",categories: ["male", "female"]}
]
}
I tried this:
var category = [];
var Count = chartData.chart;
for (var i=0; i< Count.length; i++) {
category.push({name : chartData.chart[i].name, categories : chartData.chart[i].categories})
}
Finally:
xAxis: {
categories: category
}
The category not coming properly on x axis. Does anybody have an idea why it's not?

For this you need to include library
include following library
<script src="http://blacklabel.github.io/grouped_categories/grouped-categories.js"></script>

Related

JSON add nested sub objects dynamically using JS or JQuery

I am creating a services cart at client side
where services are grouped inside 3 level of groupings like
product[SECTION] [SERVICE] [ITEM]
product['carpet']['cleaning']['room'] = {'qty':2,'price':15};
product['carpet']['cleaning']['hall'] = {'qty':1,'price':10};
product['carpet']['protecting']['hall'] = {'qty':1,'price':10};
product['carpet']['deodorize']['hall'] = {'qty':1,'price':10};
product['leather']['cleaning']['sofa'] = {'qty':1,'price':10};
want to generate above structure of json.
my text boxes looks like below notice data-section data-service data-tem and data-price
<input type="text" class="form-control input-number"
data-price="15" data-section="carpet" data-item="room" data-service="protect" />
My JS code is as below, but it adds only current item while overwriting all other services and sections.
$(function(){
$('.input-number').change(function(){
var section = $(this).attr('data-section');
var item = $(this).attr('data-item');
var service = $(this).attr('data-service');
var qty = $(this).val();
var unitprice = $(this).attr('data-unitprice');
addProduct(section,item,service,qty,unitprice);
});
});
function addProduct(section,item,service,qty,unitprice){
let products = {};
if(localStorage.getItem('products')){
products = JSON.parse(localStorage.getItem('products'));
}
products['"'+section+'"'] =
{
['"'+service+'"'] : {
['"'+item+'"'] : {
'unitprice' : unitprice, 'qty': qty
}
}
};
localStorage.setItem('products', JSON.stringify(products));
}
How can I append only instead of overwriting nested items?
EDITED
I have edited my add product function as below but still not getting desired result
function addProduct(section,item,service,qty,unitprice){
let products = {};
if(localStorage.getItem('products')){
products = JSON.parse(localStorage.getItem('products'));
}
var v = {
[service] : {
[item] :{
"qty":qty,'unitprice':unitprice
}
}
};
products.push( section, v );
localStorage.setItem('products', JSON.stringify(products));
}
Object.prototype.push = function( key, value ){
if(typeof value === 'object'){
var k = Object.keys(value)[0];
value.push( k, value[k] );
}
this[ key ] = value;
return this;
}
First of all that is not a good way to store your data.
Here's a better way to store your data.
It's much more easy to understand if you see it like an object cause in javascript it's the same thing
//example this 2 data is store the same way in javascript
var product['carpet']['cleaning']['room'] = {'qty':2,'price':15};
var product = [{
carpet: {
cleaning: {
room: {'qty':2,'price':15}
}
}
}]
// my solution would be just save section, service and item in the object, example:
var product = [];
var v = {
section: 'carpet',
service: 'cleaning',
item: 'room'
qty:2,
price:15
}
product.push(v)

How to get value only from json array using Jquery?

I am trying to get the value only from a json array. I have search some answer in stackoverflow but seems like not the one for me.
my code looks like this:
.done(function (data) {
var jdata = JSON.stringify(data['queryBuilder']);
var arrdata = JSON.parse(jdata);
var fdata = JSON.stringify(arrdata);
printtopdf(fdata);
);
//this code is from the answer posted here in stackoverflow:
function printtopdf(fdata) {
var values = Object.keys(fdata).map(function (key) { return fdata[key]; });
console.log(fdata);
}
and the result:
[
{
"rownum":2,
"rr_id":"RR2100001",
"ref_id":"UCL2100001",
"cdescription":"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"rr_status":"Pending",
"date_created":"2021-01-08 13:46:03"
}
]
I just want to get the value only, like this:
[
2,
"RR2100001",
"UCL2100001",
"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"Pending",
"2021-01-08 13:46:03"
]
Any idea? thanks.
You can achieve this using Array.prototype.map and Object.prototype.values.
const data = [
{
"rownum":2,
"rr_id":"RR2100001",
"ref_id":"UCL2100001",
"cdescription":"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"rr_status":"Pending",
"date_created":"2021-01-08 13:46:03"
}
];
// Get values for all data points
const v1 = data.map(value => Object.values(value));
console.log(v1);
// Get values for first data point
const v2 = Object.values(data.shift());
console.log(v2);

Nested Json from nested mysql queries in Nodejs/ExpressJs

I m fetching data from mysql database in nodejs/expressjs and want to create nested json from it.
I want to create Json object like this :
[
{id : 1,countryName:'USA',population:10000,
cities : [
{id:1,cityName:'NY',countryId:1},{id:2,cityName:'Chicago',countryId:1}
]
},
{id : 2,countryName:'Canada',population:20000,
cities : [
{id:1,cityName:'Toronto',countryId:2},{id:2,cityName:'Ottawa',countryId:2}
]
}
]
here is my code in expressJs but it is giving me an empty array of JSON
app.get("/checkJson",function(req,res){
var country = {};
var outerobj = {};
var outerArray = [];
conn.query("select * from country",function(err,result){
for(var i = 0 ;i<result.length;i++){
var cityobj = {};
var city = [];
conn.query("select * from city where countryId ="+result[i].id,function(err,cityResult){
for(var j = 0;j<cityResult.length;j++){
cityobj = {cityName:cityResult[j].name,countryId:cityResult[j].countryId};
city.push(cityobj);
} //end city forloop
}) //end city Query
outerobj = {id:result[i].id,countryName:result[i].name,pop:result[i].population,cities:city};
outerArray.push(outerobj);
} //end country forloop
}) // end country query
console.log(outerArray);
})
MySQL returns flat objects. We want to nest joined objects.
Let's say we have courses table, each course belongs to a department and has various course sections. We would like to have a resulting courses array that has a department object property within it and have a list of course sections.
This is a good solution from kyleladd on github
https://github.com/ravendano014/node-mysql-nesting

Convert JSON objects into"value" "value" pairs

I have a JSON object with this structure:
I am trying to get it into this format
{"123" : "Asthma", "124" : "Bronchitis".....}
I am pretty green with javascript and working with JSON. Some assistance would be great.
Thanks
Try something like this:
var arr = [{id: 1, name: 'a'},{id: 2, name: 'b'},{id: 3, name: 'c'}];
var obj = {};
for (var i=0 ; i<arr.length ; ++i) {
obj[arr[i].id] = arr[i].name;
}
console.log(obj);

Create dojox datagrid structure layout programmatically/dynamically

I want to create a dojo datagrid with a header looking like this :
As you can see I want some section headers (Section A, Section B...), containing many "subheaders" (A1, A2, A3... B1, B2...). I get all the data in a json response when I call the page. Then I was able to do two things :
First, get the data in the json to display all the subheaders, like this :
var gridStructure = [
{width:'150px', name:'Table'}
];
for(var i = 0 ; i < response.columns.length ; i++) {
for(var j = 0 ; j < response.columns[i].sections.length ; j++) {
var subColumnToAdd =
{width:'200px', name:response.columns[i].sections[j].sectionName};
gridStructure.push(subColumnToAdd);
}
}
grid.setStructure(gridStructure);
And I also was able to display a table like how I want, but not dynamically :
var gridStructure = [{
cells:[
[{width: 'auto'}],
[{
name: 'Section A',
colSpan: 2
}],
[{
name: 'A1',
field: 'col1'
}, {
name: 'A2',
field: 'col2'
}]
],
onBeforeRow : function(inDataIndex, inSubRows) {
inSubRows[0].invisible = true;
}
}];
grid.setStructure(gridStructure);
Now what I don't know to do is how to mix it, to fill the headers/subheaders with dynamic data. Thanks for your help and advices.
Try something like this:
var gridStructure = [
[
{width:'150px', name:'Table', rowSpan: 2}
]
];
for(var i = 0 ; i < response.columns.length ; i++) {
for(var j = 0 ; j < response.columns[i].sections.length ; j++) {
var subColumnToAdd =
{width:'200px', name:response.columns[i].sections[j].sectionName};
gridStructure.push(subColumnToAdd);
}
}
But that is adding the table statically... to make it completely dynamic, you'll still need something (perhaps in the data itself) that specifies the value for colSpan/rowSpan to get it to display properly.
To add the data, you just need to build a json array of your data. Each item of that array will be an object containing a single item. Should be straightforward if your data is already in this format, otherwise just create a loop and build the item dynamically.
var items = [
{ name: "First", someProperty: true},
{ name: "Second", someProperty: false}
];
Once you have it, there are many options on how to build stores:
store = new Memory({ data: items });
dataStore = new ObjectStore({ objectStore: store });
myGrid.set("store", dataStore);
or
grid = new DataGrid({
store: dataStore,
...
You can use this as a reference/example https://dojotoolkit.org/documentation/tutorials/1.9/datagrid/demo/datagrid-subrows.php