I'm new to Javascript objects and Jquery and I have no clue how I do something like this:
series: {
regions: [{
values: {
for(i = 0; i < 10; i++){
[countryname[i]] : countrycolor[i]
}
[countrynames] : countrycolor,
}
}]
}
How do I make the for loop basically print out the country names and countrycolors that I have in an array.
Im using jvectormap and the full code which im using right now for the map is:
var countrynames = "<?php if (isset($countryname)) {echo $countryname;}; ?>";
var countrycolor = "<?php if (isset($countrycolor)) {echo $countrycolor;}; ?>";
$('#world-map').vectorMap({
map: 'world_mill',
onRegionClick: function (event, code) {
window.location.href = "country.php?id=" + code;
},
series: {
regions: [{
values: {
[countrynames] : countrycolor,
}
}]
}
});
You could use reduce[1] function to achive what you want on plain javascript
{
values: countrynames.reduce(function(result, country, index) {
result[country] = countrycolor[index];
return result;
}, {});
}
[1] - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Related
I used the following code to fetch JSON data which was a success. I initialized a global array and stored one unit of that data in an array. Now somewhere in my code, there is an array nested inside an object how do I pass this array there?
var myRequest = new Request("https://script.googleusercontent.com/macros/echo?user_content_key=KW75vuIX25SoStm_K2HLVQNBRF2fx_5URDdL-vYJfUSTBaOAlMkJeWc25wjo5zdMLaznziyuqNd4B5kNs8k3tH0OxgnfssPwm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnIFtsXaNuh0rFflir-T-GWuA8AvQ2kUI-jEwpZssg8RaEHh5W9MAfgDGMRkNsN06wEWY2nZ7HPw5&lib=M_p61mp1Qy6uGkXTBzlj4kloBXIZCdEN3")
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++)
{
arr[i]=data.user[i].battingScore;
}
return arr;
});
This is where I want to use the arr:
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
title: {
text: 'Logarithmic axis demo'
},
xAxis: {
tickInterval: 1,
type: 'logarithmic'
},
yAxis: {
type: 'logarithmic',
minorTickInterval: 0.1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br />',
pointFormat: 'x = {point.x}, y = {point.y}'
},
series: [{
data:[], //here
pointStart: 1
}]
});
});
});
Note: Here, series is an array of objects but is an attribute of hello object. I want the values of arr inside data which is an array. How to do that?
If you want to gather the data before rendering the chart, you could do this.
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
arr[i]=data.user[i].battingScore;
}
return arr;
})
.then(function(scores){
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
. . .
series: [{
data:scores,
pointStart: 1
}]
});
});
});
});
Otherwise, you can define your myChart3 as a global variable and change "var myChart3=" to just "myChart3=" in your event listener. Then, you can populate the data into the existing chart using series.addPoint like this:
var myChart3;
document.addEventListener('DOMContentLoaded', function () {
myChart3 = Highcharts.chart('c', {
. . .
});
});
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
myChart3.series[0].addPoint(data.user[i].battingScore, false);
}
myChart3.redraw();
},
cache: false
});
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,
It's the first time I see a JSON like this.
I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.
I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...
I'm using scheb/yahoo-finance-api on packagist for that, if it helps.
Thanks for your help.
{
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
}
$(function(){
$("#get-data").click(function() {
//do ajax here and load data
var showData = $('#show-data');
var $data = $.getJSON("data.php", function(data) {
// $data = $data.responseText;
function buildTree(data, container) {
$data.forEach(function(node) {
var el = document.createElement(node.tag);
if (Array.isArray(node.content)) {
buildTree(node.content, el);
}
else if (typeof(node.content) == 'object') {
buildTree([node.content], el);
}
else {
el.innerHTML = node.content;
}
container.appendChild(el);
});
}
console.log($data);
buildTree($data, document.body);
});
});
});
That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)
literal notation, not Json.
You can go over this in a for in loop, something like this:
var x = {
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
}
for (var key in x) {
if (!x.hasOwnProperty(key)) continue;
var obj = x[key];
for (var prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
alert(prop + " = " + obj[prop]);
}
}
Is this what you want to achieve?
// let's assume this is your data
var data = {
query: {
count: 1,
created: "2017-06-07T12:34:44Z",
lang: "en-US",
results: {
quote: {
symbol: "APLL",
Symbol: "APLL",
LastTradePriceOnly: "0.119",
LastTradeDate: "6/6/2017",
LastTradeTime: "11:13am",
Change: "+0.023",
Open: "0.119",
DaysHigh: "0.119",
DaysLow: "0.110",
Volume: "300"
}
}
}
};
// prints one li with key and value
function printTree(key, value, container) {
var li = $('<li></li>');
if (typeof value === 'object') {
// value is a nested object, create a new <ul> element for it
li.append(key + ': ');
var ul = $('<ul></ul>');
for (var index in value) {
printTree(index, value[index], ul); // call the function recursively
}
li.append(ul);
} else {
li.text(key + ': ' + value);
}
container.append(li);
}
printTree('data', data, $('#container')); // call the function for the first time
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="container">
This is in literal notation so I assume you've already parsed it into an object. Let's call that object myObject
var myObject={
query : {
count : 1 ,
created : "2017-06-07T12:34:44Z" ,
lang : "en-US" ,
results : {
quote : {
symbol : "APLL" , Symbol : "APLL" , LastTradePriceOnly : "0.119" , LastTradeDate : "6/6/2017" , LastTradeTime : "11:13am" , Change : "+0.023" , Open : "0.119" , DaysHigh : "0.119" , DaysLow : "0.110" , Volume : "300" } } } }
You can access properties as follows:
var myCount = myObject.query.count
console.log(myCount) // logs 1
How to recover the elements of a foreach for reformed in this way:
['julie','nicola','sahra']
My code
var outPutStats = ''
client.data.forEach(function(element) {
outPutStats += [element.name];
});
.............................
.............................
xAxis: {
name: [outPutStats] // Must be ['dataName1','dataName2']
},
yAxis: {
title: {
text: null
}
},
try this:
var outputStats = [];
client.data.forEach(function(element) {
outputStats.push(element.name);
});
It's probably more semantically accurate to use Array#map instead, though, if the clients you want support it (which afaik they should if they support forEach):
var outputStats = client.data.map(function(element) { return element.name; });
If you want to copy client.data into a new array outPutStats then this will work (although I don't see the reason why, you could just use client.data):
// This must be an array
var outPutStats = [];
client.data.forEach(function(element) {
// fill the array with elements
outPutStats.push(element.name);
});
// ...
// ...
xAxis: {
name: outPutStats // outPutStats is already an array
},
yAxis: {
title: {
text: null
}
},
I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using fin-hypergrid.
There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:
aggregates = {Value: rollups.sum(11)}
I would like to change this value to return 2 decimal places and tried:
rollups.sum(11).toFixed(2)
However, it gives the error : "rollups.sum(...).toFixed is not a function"
If I try something like:
parseFloat(rollups.sum(11)).toFixed(2)
it throws the error: "can't assign to properties of (new String("NaN")): not an object"
so it has to be a function object.
May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?
(side info: rollups.sum(11) comes from a module which gives:
sum: function(columnIndex) {
return sum.bind(this, columnIndex);
}
)
Sorry I could not post sample output here due to data confidentiality issues.
However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".
window.onload = function() {
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [{
label: 'Grouping',
ctrls: [
{ name: 'treeview', checked: false, setter: toggleTreeview },
{ name: 'aggregates', checked: false, setter: toggleAggregates },
{ name: 'grouping', checked: false, setter: toggleGrouping}
]
}
];
function derivedPeopleSchema(columns) {
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' });
var columnSchema = factory.lookup('last_name');
if (columnSchema) {
columnSchema.defaultOp = 'IN';
}
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
}
var customSchema = [
{ name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true },
{ name: 'total_number_of_pets_owned', type: 'number' },
{ name: 'height', type: 'number' },
'birthDate',
'birthState',
'employed',
{ name: 'income', type: 'number' },
{ name: 'travel', type: 'number' }
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions = {
data: people1,
schema: peopleSchema,
margin: { bottom: '17px' }
},
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options) {
options = options || {};
if (data === people1 || data === people2) {
options.schema = peopleSchema;
}
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
}
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions({
//container: document.getElementById('dialog-container'),
settings: false
});
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) { // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add({
children: [{
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
}],
type: 'columnFilter'
});
}
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates = {
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
},
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates() {
if (!aggView){
aggView = new AggView(grid, {});
aggView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked) {
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
} else {
grid.setAggregateGroups([], []);
aggViewOn = false;
}
}
function toggleTreeview() {
if (this.checked) {
treeView = new TreeView(grid, { treeColumn: 'State' });
treeView.setPipeline({ includeSorter: true, includeFilter: true });
treeView.setRelation(true, true);
} else {
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
}
}
var groupView, groupViewOn = false;
function toggleGrouping(){
if (!groupView){
groupView = new GroupView(grid, {});
groupView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked){
grid.setGroups(groups);
groupViewOn = true;
} else {
grid.setGroups([]);
groupViewOn = false;
}
}
you may try:
(rollups.sum(11)).toFixed(2)
enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal
edited #2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName) {
if(aggViewOn)
{
if(config.columnName == "total_pets")
{
if(typeof(config.value) == 'number')
{
config.value = config.value.toFixed(2);
}
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
{
config.value = config.value[1].toFixed(2);
}
}
}
return grid.cellRenderers.get(rendererName);
};
I have a set of room data in json, each room data includes which site, building and floor it resides in.
The data examples are like
[
{
'site':'liverpool', 'building':'building a', 'floor':'0', 'room':'room a'
},
{
'site':'liverpool', 'building':'building a', 'floor':'1', 'room':'room b'
},
{
'site':'liverpool', 'building':'building b', 'floor':'0', 'room':'room a'
}
............
]
now I using javascript to break down this data set into a hierarchy structure, such as
{
'site':[
{
'name':'liverpool',
'buildings':[
{
'name':'building a',
'floors':[
{
'name':0,
'rooms':['room a', 'room b']
}
]
}
]
}
]
}
for me, it is still very hard to transform the raw data into the wanted structure, could someone instruct me how to do it?
I have tried with underscore, but only achieved with one hierarchy.
var groups = _.groupBy(data,function(room){
return (room.site+","+room.building+","+room.floor);
})
Assuming var data is your JSON:
var sites = [];
for(var i=0,l=data.length;i<l;i++) {
var row = data[i];
var site = false;
var building = false;
var floor = false;
// search for existing site
for(var j=0,k=sites.length;j<k;j++) {
if(sites[j].name == row.site) {
site = j;
break;
}
}
if(site === false) {
site = sites.length;
sites[site] = {
name: row.site,
buildings: []
};
}
// search for existing building
for(var j=0,k=sites[site].buildings.length;j<k;j++) {
if(sites[site].buildings[j].name == row.building) {
building = j;
break;
}
}
if(building === false) {
building = sites[site].buildings.length;
sites[site].buildings[building] = {
name: row.building,
floors: []
};
}
// search for existing floor
for(var j=0,k=sites[site].buildings[building].floors.length;j<k;j++) {
if(sites[site].buildings[building].floors[j] == row.floor) {
floor = j;
break;
}
}
if(floor === false) {
floor = sites[site].buildings[building].floors.length;
sites[site].buildings[building].floors[floor] = row.floor;
}
}
Resulting Structure:
var sites = [
{
"name":"liverpool",
"buildings":[
{
"name":"building a",
"floors":[
"0",
"1"
]
},
{
"name":"building b",
"floors":[
"0"
]
}
]
}
];
Use it:
var liverpool = sites[0];
var building_b = liverpool.buildings[1];
There are probably better ways of doing it though.