jquery tooltip showing taking json values - javascript

here is my jquery tooltip code.
var $tooltip = $("<div class='tooltip top in'><div class='tooltip-inner'></div></div>").hide().appendTo('body');
var previousPoint = null;
placeholder.on('plothover', function (event, pos, item) {
if (item) {
if (previousPoint != item.seriesIndex) {
previousPoint = item.seriesIndex;
var tip = item.series['label']+":" +item.series['percent'] + '%';
//var tip = item.series['Alert1']+":"+item.series['percent']+'%';
$tooltip.show().children(0).text(tip);
}
$tooltip.css({ top: pos.pageY + 10, left: pos.pageX + 10 });
} else {
$tooltip.hide();
previousPoint = null;
}
});
And my Json Data :
[
{
"label": "FDR Compliance",
"Assessments": "151",
"Conductedon": "101",
"OpenTasks": "141",
"charts": [
{
"label":"Low",
"data": "60",
"Alert1":"90 Day",
"Alert2":"Key Member",
"color":"#68BC31"
},
{
"label":"High",
"data": "30",
"Alert1":"Missed",
"Alert2":"YTD",
"color": "#DA5430"
},
{
"label":"Medium",
"data": "15",
"Alert1":"E & OE",
"Alert2":"Failure",
"color": "#FEE074"
}
]
}
]
In the above code if in jQuery the tool will display the data if it is:
var tip = item.series['label']+":" +item.series['percent'] + '%';
In the tooltip the value displays correctly.
I want to display the Alert1 value and not label value so when I write this code:
var tip = item.series['Alert1']+":"+item.series['percent']+'%';
in the tooltip the value says "undefined"
Help me out!!!

Related

I can not figure out why I keep getting this error

I keep getting this error code on different lines every time I run this script , but I can not figure out why? here is the source code. I will answer any questions and or can respond quickly . I'm not sure what other details to give.
$(function() {
var
bungieId = checkParams('bungieId'),
destinyId = checkParams('destinyId'),
joined = checkParams('joined'),
checkName = function(name, list) {
var m = false; // flag
console.log('Checking list for ' + name + '...');
// loop through clan usernames and check for a match
$.each(list, function(i) {
// make case insensitve
if (name.toLowerCase() === list[i].toLowerCase()) {
console.log('Confirmed: ' + list[i]);
m = true;
}
});
if (m) {
return true;
} else {
return false;
}
};
if (bungieId && destinyId && joined) {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny2/2/Account/" + destinyId + "/Character/0/Stats/UniqueWeapons/",
headers: {
"X-API-Key": apiKey
},
success: function(data) {
if (data.ErrorStatus === 'Success') {
Telesto = data.Response.weapons[0].values.uniqueWeaponKills.basic.displayValue,
TheHuckleberry = data.Response.weapons[1].values.uniqueWeaponKills.basic.displayValue,
RatKing = data.Response.weapons[2].values.uniqueWeaponKills.basic.displayValue,
Anarchy = data.Response.weapons[3].values.uniqueWeaponKills.basic.displayValue,
SUROSRegime = data.Response.weapons[4].values.uniqueWeaponKills.basic.displayValue,
Sunshot = data.Response.weapons[5].values.uniqueWeaponKills.basic.displayValue,
DARCI = data.Response.weapons[6].values.uniqueWeaponKills.basic.displayValue,
Borealis = data.Response.weapons[7].values.uniqueWeaponKills.basic.displayValue,
Thunderlord = data.Response.weapons[8].values.uniqueWeaponKills.basic.displayValue,
PolarisLance = data.Response.weapons[9].values.uniqueWeaponKills.basic.displayValue,
Crimson = data.Response.weapons[10].values.uniqueWeaponKills.basic.displayValue,
FightingLion = data.Response.weapons[11].values.uniqueWeaponKills.basic.displayValue,
TractorCannon = data.Response.weapons[12].values.uniqueWeaponKills.basic.displayValue,
LeMonarque = data.Response.weapons[13].values.uniqueWeaponKills.basic.displayValue,
GravitonLance = data.Response.weapons[14].values.uniqueWeaponKills.basic.displayValue,
VigilanceWing = data.Response.weapons[15].values.uniqueWeaponKills.basic.displayValue,
BlackTalon = data.Response.weapons[16].values.uniqueWeaponKills.basic.displayValue,
TheColony = data.Response.weapons[17].values.uniqueWeaponKills.basic.displayValue,
SleeperSimulant = data.Response.weapons[18].values.uniqueWeaponKills.basic.displayValue,
HardLight = data.Response.weapons[19].values.uniqueWeaponKills.basic.displayValue,
Merciless = data.Response.weapons[20].values.uniqueWeaponKills.basic.displayValue,
SkyburnersOath = data.Response.weapons[21].values.uniqueWeaponKills.basic.displayValue,
PrometheusLens = data.Response.weapons[22].values.uniqueWeaponKills.basic.displayValue,
Malfeasance = data.Response.weapons[23].values.uniqueWeaponKills.basic.displayValue,
OutbreakPerfected = data.Response.weapons[24].values.uniqueWeaponKills.basic.displayValue,
Jötunn = data.Response.weapons[25].values.uniqueWeaponKills.basic.displayValue,
WishEnder = data.Response.weapons[26].values.uniqueWeaponKills.basic.displayValue,
SweetBusiness = data.Response.weapons[27].values.uniqueWeaponKills.basic.displayValue,
Coldheart = data.Response.weapons[28].values.uniqueWeaponKills.basic.displayValue,
TheWardcliffCoil = data.Response.weapons[29].values.uniqueWeaponKills.basic.displayValue,
LegendofAcrius = data.Response.weapons[30].values.uniqueWeaponKills.basic.displayValue,
Wavesplitter = data.Response.weapons[31].values.uniqueWeaponKills.basic.displayValue,
WhisperoftheWorm = data.Response.weapons[32].values.uniqueWeaponKills.basic.displayValue,
Arbalest = data.Response.weapons[33].values.uniqueWeaponKills.basic.displayValue,
TwoTailedFox = data.Response.weapons[34].values.uniqueWeaponKills.basic.displayValue,
Sturm = data.Response.weapons[35].values.uniqueWeaponKills.basic.displayValue,
Riskrunner = data.Response.weapons[36].values.uniqueWeaponKills.basic.displayValue,
IzanagisBurden = data.Response.weapons[37].values.uniqueWeaponKills.basic.displayValue,
TheChaperone = data.Response.weapons[38].values.uniqueWeaponKills.basic.displayValue,
LordofWolves = data.Response.weapons[39].values.uniqueWeaponKills.basic.displayValue,
TheProspector = data.Response.weapons[40].values.uniqueWeaponKills.basic.displayValue,
Thorn = data.Response.weapons[41].values.uniqueWeaponKills.basic.displayValue,
TheLastWord = data.Response.weapons[42].values.uniqueWeaponKills.basic.displayValue,
Cerberus = data.Response.weapons[43].values.uniqueWeaponKills.basic.displayValue,
WorldlineZero = data.Response.weapons[44].values.uniqueWeaponKills.basic.displayValue,
TheQueenbreaker = data.Response.weapons[45].values.uniqueWeaponKills.basic.displayValue,
BadJuju = data.Response.weapons[46].values.uniqueWeaponKills.basic.displayValue,
Lumina = data.Response.weapons[47].values.uniqueWeaponKills.basic.displayValue,
LegendofAcrius = data.Response.weapons[48].values.uniqueWeaponKills.basic.displayValue,
TheJadeRabbit = data.Response.weapons[49].values.uniqueWeaponKills.basic.displayValue,
AceofSpades = data.Response.weapons[50].values.uniqueWeaponKills.basic.displayValue,
TrinityGhoul = data.Response.weapons[51].values.uniqueWeaponKills.basic.displayValue,
Truth = data.Response.weapons[52].values.uniqueWeaponKills.basic.displayValue,
MIDAMultiTool = data.Response.weapons[53].values.uniqueWeaponKills.basic.displayValue;
$('#player-AceofSpades').text(AceofSpades);
$('#player-TheJadeRabbit').text(TheJadeRabbit);
$('#player-TrinityGhoul').text(TrinityGhoul);
$('#player-SweetBusiness').text(SweetBusiness);
$('#player-TheWardcliffCoil').text(TheWardcliffCoil);
$('#player-Wavesplitter').text(Wavesplitter);
$('#player-TheQueenbreaker').text(TheQueenbreaker);
$('#player-PrometheusLens').text(PrometheusLens);
$('#player-Two-TailedFox').text(Two - TailedFox);
$('#player-TheJadeRabbit').text(TheJadeRabbit);
$('#player-DARCI').text(DARCI);
$('#player-TheChaperone').text(TheChaperone);
$('#player-Lumina').text(Lumina);
$('#player-LegendofAcrius').text(LegendofAcrius);
$('#player-GravitonLance').text(GravitonLance);
$('#player-SleeperSimulant').text(SleeperSimulant);
$('#player-SkyburnersOath').text(SkyburnersOath);
$('#player-Merciless').text(Merciless);
$('#player-Thorn').text(Thorn);
$('#player-LeMonarque').text(LeMonarque);
$('#player-BlackTalon').text(BlackTalon);
$('#player-TheProspector').text(TheProspector);
$('#player-Crimson').text(Crimson);
$('#player-Borealis').text(Borealis);
$('#player-PolarisLance').text(PolarisLance);
$('#player-IzanagisBurden').text(IzanagisBurden);
$('#player-Sunshot').text(Sunshot);
$('#player-Arbalest').text(Arbalest);
$('#player-WhisperoftheWorm').text(WhisperoftheWorm);
$('#player-LegendofAcrius').text(LegendofAcrius);
$('#player-TheLastWord').text(TheLastWord);
$('#player-MIDAMulti-Tool').text(MIDAMulti - Tool);
$('#player-Wish-Ender').text(Wish - Ender);
$('#player-Jötunn').text(Jötunn);
$('#player-Malfeasance').text(Malfeasance);
$('#player-PrometheusLens').text(PrometheusLens);
$('#player-OutbreakPerfected').text(OutbreakPerfected);
$('#player-Truth').text(Truth);
$('#player-Coldheart').text(Coldheart);
$('#player-Cerberus+').text(Cerberus);
$('#player-WorldlineZero').text(WorldlineZero);
$('#player-BadJuju').text(BadJuju);
$('#player-Riskrunner').text(Riskrunner);
$('#player-Thunderlord').text(Thunderlord);
$('#player-Sturm').text(Sturm);
$('#player-LordofWolves').text(LordofWolves);
$('#player-FightingLion').text(FightingLion);
$('#player-TractorCannon').text(TractorCannon);
$('#player-VigilanceWing').text(VigilanceWing);
} else {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(data);
}
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
}
});
This is the error code :
"Response": {
"weapons": [{
"referenceId": 2208405142,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 2069.0,
"displayValue": "2069"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.0,
"displayValue": "0%"
}
}
}
},
{
"referenceId": 2286143274,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 1529.0,
"displayValue": "1529"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 532.0,
"displayValue": "532"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.34793982995421846,
"displayValue": "35%"
}
}
}
},
{
"referenceId": 2362471601,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 169.0,
"displayValue": "169"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 57.0,
"displayValue": "57"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.33727810650887574,
"displayValue": "34%"
}
}
}
},
This is a Sample of the Json response Im simply trying to make the https request, and then parse it into dot notation in a java script file, and then call the objects in html.
I would say you are ether trying to access values before its been created because of asynchronous ajax or you are just not accessing the JSON correctly. I would recommend opening the chrome debugger and putting some break points in to follow the data.

How do I add and manipulate the values inside my pie chart?

I'm using http://d3pie.org/ to generate a pie chart for my web application. Now, I want to manipulate the value appearing on my chart. Currently, the values appearing have more than 4 decimals. For example, 10.35234234234 . I just want 10.3523 to appear.
Here's my current code:
function drawPie(id,from,to,C,formula){
var subArray = getSubArray(C.table,from,to);
if(Object.keys(subArray).length){
var partials = createPartials(subArray, C.attributes);
//console.log("partials -> ",partials);
formula = formula.slice(1,-1);
//console.log("formula ->" , formula);
formula = formula.split(",");
//console.log("formula ->" , formula);
var cloneFormula = formula.slice();
for( var i in partials){
if(i.substr(0,1) == "$"){
for(var j = 0; j< formula.length; j++){
formula[j] = replaceFunction(i,formula[j],partials[i]);
}
}
}
//console.log("replaced formula ->" , formula);
var data = [];
var isEmpty = true;
for(var j = 0; j< formula.length; j++){
var label = cloneFormula[j].split(/(?=[-+*\/])/)[0].split(".")[1];
var temp = {};
try{
temp.value = eval(formula[j]);
}catch(err){
temp.value = 0;
}
temp.label = partials[label + ".name"];
temp.color = partials[label + ".color"];
data.push(temp);
if(temp.value != 0){
isEmpty = false;
}
}
if(isEmpty){
return true;
}
//console.log("data ->" , data);
var pie = new d3pie(id, {
"size": {
"canvasHeight": 400,
"canvasWidth": 800, //see defect 1418
"pieOuterRadius": "88%"
},
"data": {
"content": data
},
"labels": {
"outer": {
"pieDistance": 100
},
"inner": {
"format": "value"
},
"mainLabel": {
"font": "verdana"
},
"percentage": {
"color": "#e1e1e1",
"font": "verdana",
"decimalPlaces": 0
},
"value": {
"color": "#e1e1e1",
"font": "verdana"
},
"lines": {
"enabled": true,
"color": "#cccccc"
},
"truncation": {
"enabled": true
}
},
"effects": {
"pullOutSegmentOnClick": {
"effect": "linear",
"speed": 400,
"size": 8
}
}
});
return false;
}
return true;
}
Can you help me try to modify the texts appearing inside my pie chart?
use the following to strip the number and then round it.
function strip(number) {
return (parseFloat(number).toPrecision(4));
}
example
var number = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
function strip(number) {
return (parseFloat(number).toPrecision(6));
}
window.alert(strip(number));
For the generator you are using, go to the labels section, and under the label styles / Settings you will find the option for decimal places for percentage values. Enter the number of decimal places you would like to limit the labels to.

An array of prices that represents 3 different prices for the same product

I am trying to create an array that represents three different merchants which hold different prices for the same products(represented later in the code which ones).
My logic seems off and I would like help with one example on how this should be done correctly.
Attached is my code but please take notice only to the Merchantprices and getRecipeItems part.
JS
var main = function () {
var recipeType = {
0: {"name": "cocktail", "ingredients": ["Booz","Roofis","Green Stuff"]},
1: {"name": "appetizer", "ingredients": ["Some leaves","Some veggies", "I dunno toast","Cheese or whatever"]},
2: {"name": "main course", "ingredients": ["A dead animal","its blood", "some potatoes","love","asparagus"]} ,
3: {"name": "dessert", "ingredients": ["Dough","Some Sprinkly shit", "sugar","more sugar","cream shaboogy pop"]} ,
}
var Merchantprices = {
ampm:{"ingredientPrice":recipeType[0].ingredients = 20,"sumPrice":recipeType[0] = ingredientPrice * (recipeType[0].ingredients.length)},
haCarmel:{},
tivTaam:{},
}
function getRecipeItems() {
return recipeItems = [
{
"id": "recipe0",
"title": "Grasshopper Cocktail",
"img": "../images/grasshopper-cocktail.jpg",
"ingredients": recipeType[0].ingredients,
"instructions":"shaken not stirred",
"price": {"ampmPrice":Merchantprices[0].sumPrice,"haCarmelPrice":Merchantprices[1].sumPrice,"tivTaamPrice":Merchantprices[2].sumPrice},
"type" : recipeType[0].name,
},
{
"id": "recipe1",
"title": "Beef roast with veggies",
"img": "../images/beef-roast-with-veggies.JPG",
"ingredients": recipeType[2].ingredients,
"instructions":"stuff it good",
"price": 55,
"type" : recipeType[2].name,
},
{
"id": "recipe2",
"title": "Shrimp-Fried-Rice",
"img": "../images/Shrimp-Fried-Rice.jpg",
"ingredients": recipeType[1].ingredients,
"instructions":"extra MSG",
"price": 65,
"type" : recipeType[1].name,
},
{
"id": "recipe3",
"title": "Cupcake from hell",
"img": "../images/Cupcake-Idea-pics-200x150.png",
"ingredients": recipeType[3].ingredients,
"instructions":"death is inevitable",
"price": 15,
"type" : recipeType[3].name,
},
]
}
function createRecipeItem(recipeItem) {
var recipeElement = document.createElement('div');
recipeElement.setAttribute("id", recipeItem.id);
recipeElement.setAttribute("class", recipeItem);
recipeDetailsElement = document.createElement("div");
recipeDetailsElement.setAttribute("id", recipeItem.id+"_details");
recipeDetailsElement.appendChild(createDeleteRecipe(recipeItem));
recipeDetailsElement.appendChild(createRecipePic(recipeItem));
recipeDetailsElement.appendChild(createRecipeTitle(recipeItem));
recipePreperationElement = document.createElement("div");
recipePreperationElement.setAttribute("id", recipeItem.id+"_full_details");
recipePreperationElement.appendChild(createRecipeIngredients(recipeItem));
recipePreperationElement.appendChild(createRecipeInstructions(recipeItem));
recipePreperationElement.style.display = 'none';
recipeDetailsElement.appendChild(recipePreperationElement);
recipeElement.appendChild(createUndoDeleteRecipe(recipeItem));
recipeElement.appendChild(recipeDetailsElement);
return recipeElement;
}
function createUndoDeleteRecipe(recipeItem) {
var undoButton = document.createElement('span');
undoButton.setAttribute("id", recipeItem.id + "_undo");
undoButton.setAttribute("class", "fa fa-undo", "aria-hidden", "true");
$(undoButton).hide();
$(undoButton).click(() => {
onItemDeleteUndo(recipeItem);
});
return undoButton;
}
function createDeleteRecipe(recipeItem) {
var deleteButton = document.createElement('span');
deleteButton.setAttribute("class", "fa fa-times-circle", "aria-hidden", "true");
$(deleteButton).click(() => {
onItemDelete(recipeItem);
});
return deleteButton;
}
function onItemDelete(recipeItem) {
$('#'+recipeItem.id+'_details').hide();
$('#'+recipeItem.id+'_undo').show();
}
function onItemDeleteUndo(recipeItem) {
$('#'+recipeItem.id+'_details').show();
$('#'+recipeItem.id+'_undo').hide();
}
function createRecipeTitle(recipeItem) {
var div = document.createElement('div');
div.innerHTML = recipeItem.title;
return div;
}
function createRecipeInstructions(recipeItem) {
var div = document.createElement('div');
div.innerHTML = recipeItem.instructions;
return div;
}
function createRecipePic(recipeItem) {
var recipePic = document.createElement("img");
recipePic.setAttribute("src", recipeItem.img);
recipePic.setAttribute("class", "recipe");
$(recipePic).css('margin-top', '10px');
$(recipePic).click(() => {
$('#'+recipeItem.id+"_full_details").slideToggle();
});
return recipePic;
}
function createRecipeIngredients(recipeItem) {
var ingredients = document.createElement("ul");
ingredients.setAttribute("id", recipeItem.id + "_ingredients");
ingredients.className = "ingredientsList";
recipeItem.ingredients.forEach(ingredient => {
var li = document.createElement("li");
li.className = "ingredients";
li.setAttribute("type", "checkbox");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
li.appendChild(checkbox);
var ingredientElement = document.createElement("a");
ingredientElement.innerHTML = ingredient;
li.appendChild(ingredientElement);
ingredients.appendChild(li);
})
return ingredients;
}
recipeItems = getRecipeItems();
var mainContainer = document.getElementsByClassName('mainContainer');
recipeItems.forEach(recipeItem => {
mainContainer[0].appendChild(createRecipeItem(recipeItem));
});
};
var recipeItems;
var Merchantprices;
$(document).ready(main);
Ok, so I think I got want you meant to do. Here are 2 solutions :
Keep all in one place
function getRecipeItems() {
return recipeItems = [
{
"id": "recipe0",
// ...
"price": {
default: 8,
ampm: 10,
// -- haCarmel: 12, -- Let's omit this one
tivTaam: 15,
get: function( merchant ) {
return this[merchant] ? this[merchant] : default;
}
}
},
// ...
]
}
// ---------------------------------------
// Usage
// ---------------------------------------
// Result : 8 (default price, as you didn't specify the merchant).
getRecipeItems()[0].price.get();
// Result : 10.
getRecipeItems()[0].price.get("ampm");
// Result : 8 (default, as you didn't set this value).
getRecipeItems()[0].price.get("haCarmel");
Merchant's magic calculations
You could also set a default price, but send it to the merchant and alter it.
// Price
"price": {
default: 8,
get: function( merchant ) {
return Merchants[ merchant ]
? Merchants[ merchant ].getPrice( this.default )
: this.default;
}
}
// Merchants
Merchants {
ampm: {
//...
getPrice: function( price ){
return price + itemRarity - discount + etc;
}
},
// ...
};
In both cases, ...
You should create an object for the Merchant, RecipeItem and RecipeItemPrice. Your code will be more clean and you wouldn't create an instance of the get() function each time you create a price. Well, you should do that with ALL your game objects. :)
// Price
var RecipeItemPrice = function( value, ... ) {
this.default = value;
};
RecipeItemPrice.prototype.get = function() {
// For example, if you take the second choice :
return Merchants[ merchant ]
? Merchants[ merchant ].getPrice( this.default )
: this.default;
};

Dimple.js doesn't like my Array

I have data.json in this format:
{
"Users": [
{
"userName": "Herbie",
"weigh-in data": [
{ "date": "2016.01.04", "weight": "114.3" },
{ "date": "2016.01.05", "weight": "114.6" },
{ "date": "2016.01.06", "weight": "114.9" }
]
},
{
"userName": "Wayne",
"weigh-in data": [
{ "date": "2016.02.01", "weight": "120.3" },
{ "date": "2016.02.05", "weight": "123.6" },
{ "date": "2016.02.06", "weight": "123.9" }
]
}
]
}
// etc., more user objects
In my application: a selection of a user is made, an ajax call gets this data, I loop thru it to get only the selected user's weigh-in data, and I'm successfully rendering this data to a table.
Now I'm trying to use the same result in a Dimple chart but Dimple evidently doesn't like my chartData array:
var dataObj = JSON.parse(jsonData);
var usersArray = dataObj.Users;
var chartData = [];
// etc. SNIP
for (var obj of usersArray) {
if (obj.userName === selUser) { // weigh-ins of the selected user only
dataRows.innerHTML = "";
for (var i = 0, j = selUserData.length; i < j; i++) {
var dataDate = selUserData[i].date;
var dataWeight = selUserData[i].weight;
chartData.push('{ "User"' + ': ' + '"'+selUser+'", ' + '"Date":' + ' ' + '"'+dataDate+'", ' + '"Weight":' + ' ' + '"'+dataWeight+'" }');
// SNIP: build rows from the data, load up the table, no problem
dataRows.innerHTML += row;
} // selUserData loop
var svg = dimple.newSvg("#chartContainer", 800, 600);
var chart = new dimple.chart(svg, chartData);
chart.setBounds(60, 30, 505, 305);
var x = chart.addCategoryAxis("x", "Date");
x.addOrderRule("Dates");
var y = chart.addCategoryAxis("y", "Weight");
y.addOrderRule("Weights");
var s = chart.addSeries("weigh-ins", dimple.plot.line);
chart.draw();
... which results in a non-chart. However, if I console.log or alert(chartData) and set the result as chartData, i.e.:
var chartData = [
{ "User": "Wayne", "Date": "2016.02.01", "Weight": "180.3" },
{ "User": "Wayne", "Date": "2016.02.05", "Weight": "123.6" },
{ "User": "Wayne", "Date": "2016.02.06", "Weight": "153.9" }
]
... then I get a chart, ergo my confusion.
Any insight greatly appreciated,
Whiskey
You're pushing the JSON into your array as strings not objects, it should be:
chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });
Which has the added benefit of being much easier to read!

loop through json javascript

I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);

Categories