Array inside javascript property - javascript

function initialise() {
doubleCount = 0;
playerturn = 1;
hotelrating = 0;
flipped = 0;
//setRent();
//createPlayers();
//createPositions();
//createCards();
//createSets();
//drawBoard();
//starplugin();
//setPrices();
}
function playgame() {
setPrices();
clearContent();
rollDice(); //two dice rolls
drawDice(); //displays the dice
setPosition(); //update player position
movePiece();
checkForSale();
checkDouble();
}
function starplugin() {
$('#star').raty({
path: 'lib/img/',
cancel: true,
cancelHint: 'remove my rating!',
cancelPlace: 'right'
});
$("#star > img").click(function () {
hotelrating = $(this).attr("alt");
});
}
function clearContent() {
if (flipped === 1) {
//$(".cards").flippyReverse();
$(".cards").flippy({
color_target: "#F8F8F8",
duration: "500"
});
flipped = 0;
}
$("#drawncardtitle").text("");
$("#drawncard").text("");
$("#buildsets1").hide();
$("#buildsets2").hide();
$('.buildsets').find('option').remove();
}
function canBuild() {
var set = ["brown", "blue", "pink", "orange", "red", "yellow", "green", "navy"];
var buildablesets = [
[""],
[""],
[""]
];
for (var i = 0; i < set.length; i++) {
if (doesOwnSet('player' + playerturn, set[i])) {
buildablesets[playerturn].push(set[i]);
}
}
buildablesetsx = buildablesets[playerturn];
if (buildablesetsx.length > 1) {
$(".buildmenu").toggle();
$("#buildsets" + playerturn).show();
buildsets = $("#buildsets" + playerturn);
for (k = 1; k < buildablesets[playerturn].length; k++) {
buildsets.append("<option value='" + buildablesetsx[k] + "'>" + buildablesetsx[k] + "</option>");
}
} else {
$(".buildmenu").hide();
}
}
function build() {
var setname = $('#buildsets' + playerturn).find(":selected").text();
var balance = players['player' + playerturn].balance;
var currentRating = sets[setname].rating;
var ratingToAdd = hotelrating - currentRating;
var cost = sets[setname].cost * ratingToAdd;
if (hotelrating < currentRating) {
alert("Sorry mate, you can't downgrade");
}
if (cost > balance) {
alert("Sorry mate, you can't afford that!");
} else {
players['player' + playerturn].balance = balance - cost;
sets[setname].rating = hotelrating;
}
$(".buildmenu").hide();
}
function doesOwnSet(player, type) {
return Object.keys(positions)
.map(function (key) {
return positions[key];
})
.filter(function (pos) {
return pos.type === type;
})
.every(function (pos) {
return pos.owner === player;
});
}
function rollDice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
dice1 = x;
dice2 = y;
dicetotal = dice1 + dice2;
}
function drawDice() {
$('.dice1').css('background-image', 'url(img/dice/' + dice1 + '.png)');
$('.dice2').css('background-image', 'url(img/dice/' + dice2 + '.png)');
}
function drawBoard() {
var set = ["brown", "blue", "pink", "orange", "red", "yellow", "green", "navy"];
for (var i = 0; i < set.length; i++) {
var setcolor = sets[set[i]].color;
if (set[i] == "yellow") {
$('.yellow').css('color', 'black');
}
$('.' + set[i]).css('background', setcolor);
}
}
function setPosition() {
players['player' + playerturn].currentpos = players['player' + playerturn].startpos + dicetotal;
players['player' + playerturn].prevpos = players['player' + playerturn].currentpos - dicetotal;
currentposition = players['player' + playerturn].currentpos;
if (currentposition >= 40) {
var balance = players['player' + playerturn].balance;
players['player' + playerturn].balance = balance + 200;
$("#debug2").text("+ $200");
if (currentposition > 40) {
players['player' + playerturn].currentpos = currentposition - 40;
}
}
if (currentposition == 30) {
players['player' + playerturn].currentpos = 10;
}
players['player' + playerturn].startpos = players['player' + playerturn].currentpos;
title = positions['position' + players['player' + playerturn].currentpos].title;
}
function movePiece() {
var x = "#piece" + playerturn + "pos" + players['player' + playerturn].currentpos;
var y = "#piece" + playerturn + "pos" + players['player' + playerturn].prevpos;
$(x).slideToggle();
$(y).slideToggle();
}
function checkForSale() {
var forsale = positions['position' + players['player' + playerturn].currentpos].forsale;
if (forsale == "y") {
checkOwner();
} else {
checkType();
}
}
function checkOwner() {
var owner = positions['position' + players['player' + playerturn].currentpos].owner;
if (owner == "none") {
assignOwner();
} else {
payRent();
}
}
function payRent() {
var currentpos = players['player' + playerturn].currentpos;
var balance = players['player' + playerturn].balance;
var type = positions['position' + players['player' + playerturn].currentpos].type;
if (type == "utility") {
var rent = 4 * dicetotal;
} else {
var rent = positions['position' + currentpos].rent;
}
players['player' + playerturn].balance = balance - rent;
}
function assignOwner() {
var price = positions['position' + players['player' + playerturn].currentpos].price;
var balance = players['player' + playerturn].balance;
var title = positions['position' + players['player' + playerturn].currentpos].title;
players['player' + playerturn].balance = balance - price;
positions['position' + players['player' + playerturn].currentpos].owner = "player" + playerturn;
//positions['position'+players['player'+playerturn].currentpos].price = positions['position'+players['player'+playerturn].currentpos].rent;
$("#owns" + playerturn).append(title + '</br>');
}
function checkType() {
var balance = players['player' + playerturn].balance;
var type = positions['position' + players['player' + playerturn].currentpos].type;
if (type == "tax") {
var tax = positions['position' + players['player' + playerturn].currentpos].tax;
players['player' + playerturn].balance = balance - tax;
$("#debug2").text("- $" + tax);
} else {
if (type == "chance") {
chanceCard();
} else if (type == "chest") {
chestCard();
}
}
}
function chanceCard() {
var balance = players['player' + playerturn].balance;
var x = Math.floor(Math.random() * ((16 - 1) + 1) + 1);
var title = chancecards['chance' + x].title;
var type = chancecards['chance' + x].type;
var bill = chancecards['chance' + x].bill;
var bonus = chancecards['chance' + x].bonus;
if (type == "bill") {
players['player' + playerturn].balance = balance - bill;
$("#debug2").text("- $" + bill);
} else if (type == "bonus") {
players['player' + playerturn].balance = balance + bonus;
$("#debug2").text("+ $" + bonus);
} else if (type == "move") {
var newposition = chancecards['chance' + x].newposition;
var currentposition = players['player' + playerturn].currentpos;
if (newposition == 40) { //this if the player has to "advance to go"
advanceToGo();
} else if (newposition < currentposition) { //if the new position is less than the current one it means the player has to go past go
players['player' + playerturn].balance = balance + 200;
$("#debug2").text("+ $200");
}
players['player' + playerturn].prevpos = players['player' + playerturn].currentpos;
players['player' + playerturn].currentpos = newposition;
players['player' + playerturn].startpos = players['player' + playerturn].currentpos;
movePiece();
checkForSale();
} else if (title == "Go back 3 spaces") {
players['player' + playerturn].prevpos = players['player' + playerturn].currentpos;
players['player' + playerturn].currentpos = players['player' + playerturn].currentpos - 3;
players['player' + playerturn].startpos = players['player' + playerturn].currentpos;
movePiece();
checkForSale();
}
$(".cards").css('display', 'block');
$(".cards").flippy({
color_target: "#F8F8F8",
duration: "500",
verso: '<span id="cardtitle">Chance</span><span id="cardinfo"> ' + title + '</span>'
});
flipped = 1;
}
function chestCard() {
var balance = players['player' + playerturn].balance;
var x = Math.floor(Math.random() * ((14 - 1) + 1) + 1);
var title = chestcards['chest' + x].title;
var chesttype = chestcards['chest' + x].type;
var bill = chestcards['chest' + x].bill;
var bonus = chestcards['chest' + x].bonus;
if (chesttype == "bill") {
players['player' + playerturn].balance = balance - bill;
$("#debug2").text("- $" + bill);
} else if (chesttype == "bonus") {
players['player' + playerturn].balance = balance + bonus;
$("#debug2").text("+ $" + bonus);
} else if (chesttype == "move") {
var newposition = chestcards['chest' + x].newposition;
var currentposition = players['player' + playerturn].currentpos;
if (newposition == 40) { //this if the player has to "advance to go"
advanceToGo();
} else if (newposition < currentposition) { //if the new position is less than the current one it means the player has to go past go
players['player' + playerturn].balance = balance + 200;
$("#debug2").text("+ $200");
}
players['player' + playerturn].prevpos = players['player' + playerturn].currentpos;
players['player' + playerturn].currentpos = newposition;
players['player' + playerturn].startpos = players['player' + playerturn].currentpos;
movePiece();
checkForSale();
}
//$("#cardtitle").text("Community Chest");
//$("#cardinfo").text(title);
$(".cards").css('display', 'block');
$(".cards").flippy({
color_target: "#F8F8F8",
duration: "500",
verso: '<span id="cardtitle">Community Chest</span><span id="cardinfo"> ' + title + '</span>'
});
flipped = 1;
}
function advanceToGo() {
var balance = players['player' + playerturn].balance;
players['player' + playerturn].balance = balance + 200;
$("#debug2").text("+ $200");
}
function checkDouble() {
if (dice1 == dice2) {
doubleCount++;
if (doubleCount == 3) {
var currentpossition = players['player' + playerturn].currentpos;
players['player' + playerturn].currentpos = 10;
changeTurn();
}
} else {
changeTurn();
doubleCount = 0;
}
}
function changeTurn() {
if (playerturn == 1) {
playerturn = 2;
$("#roll1").prop("disabled", true);
$("#roll2").prop("disabled", false);
$(".buildmenu").hide();
canBuild();
} else {
playerturn = 1;
$("#roll2").prop("disabled", true);
$("#roll1").prop("disabled", false);
$(".buildmenu").hide();
canBuild();
}
}
function createPlayers() {
players = {
player1: {
currentpos: 0,
prevpos: 0,
startpos: 0,
balance: 1500
},
player2: {
currentpos: 0,
prevpos: 0,
startpos: 0,
balance: 1500
}
};
}
function createPositions() {
positions = {
position1: {
title: "Cairo",
type: "brown",
owner: "player1",
price: 60,
rent: [2, 10, 30, 90, 160, 250],
rating: 0,
forsale: "y"
},
position3: {
title: "Vienna",
type: "brown",
owner: "player1",
price: 60,
rent: [2, 20, 60, 180, 320, 450],
rating: 0,
forsale: "y"
},
position5: {
title: "Schiphol",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position6: {
title: "Brussels",
type: "blue",
owner: "none",
price: 100,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position8: {
title: "Oslo",
type: "blue",
owner: "none",
price: 100,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position9: {
title: "Zurich",
type: "blue",
owner: "none",
price: 120,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position11: {
title: "Amsterdam",
type: "pink",
owner: "none",
price: 140,
rent: [10, 50, 150, 450, 625, 750],
rating: 0,
forsale: "y"
},
position13: {
title: "Bangkok",
type: "pink",
owner: "none",
price: 140,
rent: [10, 50, 150, 450, 625, 750],
rating: 0,
forsale: "y"
},
position14: {
title: "Istanbul",
type: "pink",
owner: "none",
price: 160,
rent: [12, 60, 180, 500, 700, 900],
rating: 0,
forsale: "y"
},
position15: {
title: "Charles de Gaulle",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position16: {
title: "Hong Kong",
type: "orange",
owner: "none",
price: 180,
rent: [14, 70, 200, 550, 750, 950],
rating: 0,
forsale: "y"
},
position18: {
title: "Madrid",
type: "orange",
owner: "none",
price: 180,
rent: [14, 70, 200, 550, 750, 950],
rating: 0,
forsale: "y"
},
position19: {
title: "Sydney",
type: "orange",
owner: "none",
price: 200,
rent: [16, 80, 220, 600, 800, 100],
rating: 0,
forsale: "y"
},
position21: {
title: "Toronto",
type: "red",
owner: "none",
price: 220,
rent: [18, 90, 250, 700, 875, 1050],
rating: 0,
forsale: "y"
},
position23: {
title: "Mumbai",
type: "red",
owner: "none",
price: 220,
rent: [18, 90, 250, 700, 875, 1050],
rating: 0,
forsale: "y"
},
position24: {
title: "Rome",
type: "red",
owner: "none",
price: 240,
rent: [20, 100, 300, 750, 925, 1100],
rating: 0,
forsale: "y"
},
position25: {
title: "Heathrow",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position26: {
title: "Rio",
type: "yellow",
owner: "none",
price: 240,
rent: [22, 110, 330, 800, 975, 1150],
rating: 0,
forsale: "y"
},
position27: {
title: "Tokyo",
type: "yellow",
owner: "none",
price: 240,
rent: [22, 110, 330, 800, 975, 1150],
rating: 0,
forsale: "y"
},
position29: {
title: "Paris",
type: "yellow",
owner: "none",
price: 280,
rent: [24, 120, 360, 850, 1025, 1200],
rating: 0,
forsale: "y"
},
position31: {
title: "Berlin",
type: "green",
owner: "none",
price: 300,
rent: [26, 130, 390, 900, 1100, 1275],
rating: 0,
forsale: "y"
},
position32: {
title: "Bejing",
type: "green",
owner: "none",
price: 300,
rent: [26, 130, 390, 900, 1100, 1275],
rating: 0,
forsale: "y"
},
position34: {
title: "Moscow",
type: "green",
owner: "none",
price: 320,
rent: [28, 150, 450, 1000, 1200, 1400],
rating: 0,
forsale: "y"
},
position35: {
title: "John F Kennedy",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position37: {
title: "New York",
type: "navy",
owner: "player2",
price: 350,
rent: [35, 175, 500, 1100, 1300, 1500],
rating: 0,
forsale: "y"
},
position39: {
title: "London",
type: "navy",
owner: "player2",
price: 400,
rent: [50, 200, 600, 1400, 1700, 2000],
rating: 0,
forsale: "y"
},
position12: {
title: "Electro",
type: "utility",
owner: "none",
price: 150,
rent: 10,
rating: 0,
forsale: "y"
},
position28: {
title: "Nuclear",
type: "utility",
owner: "none",
price: 150,
rent: 10,
rating: 0,
forsale: "y"
},
position2: {
title: "Community Chest",
type: "chest"
},
position17: {
title: "Community Chest",
type: "chest"
},
position33: {
title: "Community Chest",
type: "chest"
},
position7: {
title: "Chance",
type: "chance"
},
position22: {
title: "Chance",
type: "chance"
},
position36: {
title: "Chance",
type: "chance"
},
position10: {
title: "Jailhouse",
type: "jail"
},
position20: {
title: "Coffee House",
type: "coffee"
},
position30: {
title: "Go to Jail",
type: "jail"
},
position40: {
title: "Go",
type: "home"
},
position4: {
title: "Income Tax",
type: "tax",
tax: 200
},
position38: {
title: "Super Tax",
type: "tax",
tax: 100
}
};
}
function createCards() {
chancecards = {
chance1: {
title: "Advance to go",
type: "move",
newposition: 40
},
chance2: {
title: "Advance to London",
type: "move",
newposition: 39
},
chance4: {
title: "Your ass is going to jail",
type: "move",
newposition: 10
},
chance9: {
title: "Advance to Rome",
type: "move",
newposition: 24
},
chance10: {
title: "Advance to Charles de Gaulle",
type: "move",
newposition: 15
},
chance11: {
title: "Advance to Amsterdam",
type: "move",
newposition: 11
},
chance6: {
title: "Go back 3 spaces",
type: "movex",
newposition: -3
},
chance14: {
title: "No drink and driving mate1",
type: "bill",
bill: 20
},
chance15: {
title: "Get out of Jail free card",
type: "bill",
bill: 150
},
chance7: {
title: "Pay school fees",
type: "bill",
bill: 150
},
chance12: {
title: "Speeding fine",
type: "bill",
bill: 150
},
chance5: {
title: "Bank pays you dividend",
type: "bonus",
bonus: 40
},
chance13: {
title: "You have won the competition",
type: "bonus",
bonus: 200
},
chance16: {
title: "Your building loan matures",
type: "bonus",
bonus: 200
},
chance3: {
title: "You are assessed for street repairs $40 per house $115 per hotel",
type: "billx"
},
chance8: {
title: "House repairs $25 per house $100 per hotel",
type: "billx"
}
};
chestcards = {
chest1: {
title: "Advance to go",
type: "move",
newposition: 40,
bonus: 200
},
chest2: {
title: "Advance to Cairo",
type: "move",
newposition: 1
},
chest3: {
title: "Go to Jail",
type: "move",
newposition: 10
},
chest4: {
title: "Pay hospital fees",
type: "bill",
bill: 100
},
chest5: {
title: "Pay doctor fees",
type: "bill",
bill: 50
},
chest6: {
title: "Pay insurance premium",
type: "bill",
bill: 50
},
chest7: {
title: "Bank error. Collect $200",
type: "bonus",
bonus: 200
},
chest8: {
title: "Annuity matures. Collect $100",
type: "bonus",
bonus: 100
},
chest9: {
title: "You inherit $100",
type: "bonus",
bonus: 100
},
chest10: {
title: "From sale of stock you get $50",
type: "bonus",
bonus: 50
},
chest11: {
title: "Preference shares: $25",
type: "bonus",
bonus: 25
},
chest12: {
title: "You have won second prize in a beauty contest. Collect $10.",
type: "bonus",
bonus: 10
},
chest13: {
title: "It is your birthday. Collect $10.",
type: "bonus",
bonus: 10
},
chest14: {
title: "You win the lottery. Collect $10",
type: "bonus",
bonus: 10
}
};
}
function createSets() {
sets = {
brown: {
cost: 100,
rating: 0,
color: "#996600"
},
blue: {
cost: 150,
rating: 0,
color: "#99CCFF"
},
pink: {
cost: 300,
rating: 0,
color: "#FF0066"
},
orange: {
cost: 300,
rating: 0,
color: "#FF6600"
},
red: {
cost: 450,
rating: 0,
color: "#CC0000"
},
yellow: {
cost: 450,
rating: 0,
color: "#FFFF00"
},
green: {
cost: 600,
rating: 0,
color: "#006600"
},
navy: {
cost: 400,
rating: 0,
color: "#003399"
}
};
}
What is wrong with my code? In the console log i get the following error "Uncaught SyntaxError: Unexpected token [ ". It is something to do with the rent property? I am sorry if the question was not clear, didn't know how to ask it.

alert(positions['position1'].rent[0])
Put quotation marks around the 'position1'.
I also recommend that when there is only one rent, as in position 25, you still have it in an array. So like: rent : [25]
Also, in the first line in the function, do this:
window.positions = { /* ... your positions ... */ }

You need to put quotes around the positions, also you need to call the function:
createPositions()
alert(positions["position1"].rent[0]);
Here is a working fiddle: http://jsfiddle.net/YRJCP/

you have made various mistake to declare your javascript object.
First you have declared the javascript object inside a function but you did not return the javascript object when you are calling the function.
Either you can return the javascript object from the function or you can remove the fucntion and just declare the objects inside sript tag
please look my below changes. it shall work now.
var positions = {
position1: {
title: "Cairo",
type: "brown",
owner: "player1",
price: 60,
rent: [2, 10, 30, 90, 160, 250],
rating: 0,
forsale: "y"
},
position3: {
title: "Vienna",
type: "brown",
owner: "player1",
price: 60,
rent: [2, 20, 60, 180, 320, 450],
rating: 0,
forsale: "y"
},
position5: {
title: "Schiphol",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position6: {
title: "Brussels",
type: "blue",
owner: "none",
price: 100,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position8: {
title: "Oslo",
type: "blue",
owner: "none",
price: 100,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position9: {
title: "Zurich",
type: "blue",
owner: "none",
price: 120,
rent: [6, 30, 90, 270, 400, 550],
rating: 0,
forsale: "y"
},
position11: {
title: "Amsterdam",
type: "pink",
owner: "none",
price: 140,
rent: [10, 50, 150, 450, 625, 750],
rating: 0,
forsale: "y"
},
position13: {
title: "Bangkok",
type: "pink",
owner: "none",
price: 140,
rent: [10, 50, 150, 450, 625, 750],
rating: 0,
forsale: "y"
},
position14: {
title: "Istanbul",
type: "pink",
owner: "none",
price: 160,
rent: [12, 60, 180, 500, 700, 900],
rating: 0,
forsale: "y"
},
position15: {
title: "Charles de Gaulle",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position16: {
title: "Hong Kong",
type: "orange",
owner: "none",
price: 180,
rent: [14, 70, 200, 550, 750, 950],
rating: 0,
forsale: "y"
},
position18: {
title: "Madrid",
type: "orange",
owner: "none",
price: 180,
rent: [14, 70, 200, 550, 750, 950],
rating: 0,
forsale: "y"
},
position19: {
title: "Sydney",
type: "orange",
owner: "none",
price: 200,
rent: [16, 80, 220, 600, 800, 100],
rating: 0,
forsale: "y"
},
position21: {
title: "Toronto",
type: "red",
owner: "none",
price: 220,
rent: [18, 90, 250, 700, 875, 1050],
rating: 0,
forsale: "y"
},
position23: {
title: "Mumbai",
type: "red",
owner: "none",
price: 220,
rent: [18, 90, 250, 700, 875, 1050],
rating: 0,
forsale: "y"
},
position24: {
title: "Rome",
type: "red",
owner: "none",
price: 240,
rent: [20, 100, 300, 750, 925, 1100],
rating: 0,
forsale: "y"
},
position25: {
title: "Heathrow",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position26: {
title: "Rio",
type: "yellow",
owner: "none",
price: 240,
rent: [22, 110, 330, 800, 975, 1150],
rating: 0,
forsale: "y"
},
position27: {
title: "Tokyo",
type: "yellow",
owner: "none",
price: 240,
rent: [22, 110, 330, 800, 975, 1150],
rating: 0,
forsale: "y"
},
position29: {
title: "Paris",
type: "yellow",
owner: "none",
price: 280,
rent: [24, 120, 360, 850, 1025, 1200],
rating: 0,
forsale: "y"
},
position31: {
title: "Berlin",
type: "green",
owner: "none",
price: 300,
rent: [26, 130, 390, 900, 1100, 1275],
rating: 0,
forsale: "y"
},
position32: {
title: "Bejing",
type: "green",
owner: "none",
price: 300,
rent: [26, 130, 390, 900, 1100, 1275],
rating: 0,
forsale: "y"
},
position34: {
title: "Moscow",
type: "green",
owner: "none",
price: 320,
rent: [28, 150, 450, 1000, 1200, 1400],
rating: 0,
forsale: "y"
},
position35: {
title: "John F Kennedy",
type: "airport",
owner: "none",
price: 200,
rent: 25,
rating: 0,
forsale: "y"
},
position37: {
title: "New York",
type: "navy",
owner: "player2",
price: 350,
rent: [35, 175, 500, 1100, 1300, 1500],
rating: 0,
forsale: "y"
},
position39: {
title: "London",
type: "navy",
owner: "player2",
price: 400,
rent: [50, 200, 600, 1400, 1700, 2000],
rating: 0,
forsale: "y"
},
position38: {
title: "Super Tax",
type: "tax",
tax: 100
}
};
second you are accessing the object in a wrong way
alert(positions.position1.rent[0]); //this should print 2

Related

Filter in Array into Array

I have a array of Object like this:
data() {
return {
searchVariant: null,
variantList: ["red", "green", "blue"],
products: [
{
id: 1,
title: "adipisicing elit.",
description: "ipsa deleniti.",
variants: [
{ id: 1, color: "red", size: "xl", price: 150, inStock: 150 },
{ id: 2, color: "blue", size: "xl", price: 46, inStock: 4 },
{ id: 3, color: "gray", size: "sm", price: 50, inStock: 50 },
],
},
{
id: 2,
title: "amet consecteturt.",
description: "id quas perspiciatis deserunt.",
variants: [
{ id: 1, color: "red", size: "xl", price: 150, inStock: 150 },
{ id: 2, color: "blue", size: "xl", price: 46, inStock: 4 },
{ id: 3, color: "green", size: "sm", price: 50, inStock: 50 },
],
},
],
};
}
While I will select a variant like green in select-option, Row Number 2 will show in the table search list.
I am using Vuejs to do this:
queryResults() {
if(this.searchVariant) {
return this.products.filter((item)=> {
return item.variants.filter((variant) => {
return this.searchVariant.toLowerCase().split(' ').every(v => variant.color.toLowerCase().includes(v))
})
})
}
else{
return this.products;
}
}
You only need to check if every object in the array has some variant with the color matching your search:
const products = [
{
id: 1,
title: 'adipisicing elit.',
description: 'ipsa deleniti.',
variants: [
{id: 1, color: 'red', size: 'xl', price: 150, inStock: 150},
{id: 2, color: 'blue', size: 'xl', price: 46, inStock: 4},
{id: 3, color: 'gray', size: 'sm', price: 50, inStock: 50}
]
},
{
id: 2,
title: 'amet consecteturt.',
description: 'id quas perspiciatis deserunt.',
variants: [
{id: 1, color: 'red', size: 'xl', price: 150, inStock: 150},
{id: 2, color: 'blue', size: 'xl', price: 46, inStock: 4},
{id: 3, color: 'green', size: 'sm', price: 50, inStock: 50}
]
}
];
const searchVariant = 'green';
const result = products.filter(item =>
item.variants.some(variant =>
searchVariant.toLowerCase().includes(variant.color)
)
);
console.log(result);
You can try something like this
queryResults() {
if(this.searchVariant) {
return this.products.filter((item)=> {
item.variants.some(variant =>
variant.color.toLowerCase() === searchVariant.toLowerCase())
}
}
else{
return this.products;
}
}

How to show only first and last labels in CanvasJS

I need to show first and last labels only in CanvasJS. It's always showing all the labels but my requirement is to show only first and last. Is there any way out to do so?
You can use axisY labelFormatter to do so.
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Chart showing only First and Last Axis Labels",
},
axisY: {
tickColor: "transparent",
labelFormatter: function(e){
if(e.chart.axisY[0].minimum === e.value || e.chart.axisY[0].maximum === e.value)
return e.value;
return "";
}
},
data: [{
type: "column",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}]
});
chart.render();
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 260px; width: 100%;"></div>
You can also try hiding all axis-labels and add stripLines at the minimum and maximum.
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Chart showing only First and Last Axis Labels",
},
axisX: {
valueFormatString: "####"
},
axisY:[{
tickColor: "transparent",
labelFontColor: "transparent"
}],
axisY2:[{
tickColor: "transparent",
labelFontColor: "transparent"
}],
data: [
{
type: "column",
showInLegend: true,
name: "Axis Y-1",
xValueFormatString: "####",
dataPoints: [
{ x: 2006, y: 6 },
{ x: 2007, y: 2 },
{ x: 2008, y: 5 },
{ x: 2009, y: 7 },
{ x: 2010, y: 1 },
{ x: 2011, y: 5 },
{ x: 2012, y: 5 },
{ x: 2013, y: 2 },
{ x: 2014, y: 2 }
]
},
{
type: "column",
showInLegend: true,
axisYType: "secondary",
//axisYIndex: 0, //Defaults to Zero
name: "Axis Y2-1",
xValueFormatString: "####",
dataPoints: [
{ x: 2006, y: 12 },
{ x: 2007, y: 20 },
{ x: 2008, y: 28 },
{ x: 2009, y: 34 },
{ x: 2010, y: 24 },
{ x: 2011, y: 45 },
{ x: 2012, y: 15 },
{ x: 2013, y: 34 },
{ x: 2014, y: 22 }
]
}
]
});
chart.render();
addStripLine(chart);
function addStripLine(chart){
for(var i = 0; i < chart.axisY.length; i++){
min = chart.axisY[i].get("minimum");
max = chart.axisY[i].get("maximum");
chart.axisY[i].addTo("stripLines", {value: min, color: "black", label: min, labelFontColor: "black", labelBackgroundColor: "transparent", labelPlacement: "outside"});
chart.axisY[i].addTo("stripLines", {value: max, color: "black", label: max, labelFontColor: "black", labelBackgroundColor: "transparent", labelPlacement: "outside"});
}
for(var i = 0; i < chart.axisY2.length; i++){
min = chart.axisY2[i].get("minimum");
max = chart.axisY2[i].get("maximum");
chart.axisY2[i].addTo("stripLines", {value: min, color: "black", label: min, labelFontColor: "black", labelBackgroundColor: "transparent", labelPlacement: "outside"});
chart.axisY2[i].addTo("stripLines", {value: max, color: "black", label: max, labelFontColor: "black", labelBackgroundColor: "transparent", labelPlacement: "outside"});
}
}
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 260px; width: 100%;"></div>

Highcharts display percentage of hidden series

I am working with one of the Highcharts examples trying to get it to display percentage values of a hidden series.
Highcharts.chart('container', {
chart: {
type: 'area'
},
title: {
text: 'Historic and Estimated Worldwide Population Distribution by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: ['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: 'Percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.percentage:.1f}%</b><br/>',
split: true
},
plotOptions: {
area: {
stacking: 'percent',
lineColor: '#ffffff',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#ffffff'
}
}
},
series: [{
name: 'Total',
data: [1000, 2000, 3000, 4000, 5000, 6000, 10500],
visable: false
}, {
name: 'Asia',
data: [502, 635, 809, 947, 1402, 3634, 5268]
}, {
name: 'Africa',
data: [106, 107, 111, 133, 221, 767, 1766]
}, {
name: 'Europe',
data: [163, 203, 276, 408, 547, 729, 628]
}, {
name: 'America',
data: [18, 31, 54, 156, 339, 818, 1201]
}, {
name: 'Oceania',
data: [2, 2, 2, 6, 13, 30, 46]
}]
});
For example in the sample code I would like to display the percentage values of Asia, Africa, Europe, America, and Oceania in terms of the series Total. So the first point for Asia would read: "Asia: 50.2%". I would also like the Total series to be completely hidden i.e. not visible in the legends on the bottom. Note that the total does not have to be a series if there is a better way of doing it, it is just the most convenient place to put it.
I think that what you are look for :
...
tooltip: {
shared:true,
formatter:function(){
var myTooltip = '<b>' + this.x + '</b>',
value,
total = 0; // Total will be calculeted from series values
(this.points).forEach(function(item){
total+=item.y; // Total incrementing
});
(this.points).forEach(function(item){
value = ((item.y / total) * 100).toFixed(2);
myTooltip += '<br/>' + item.series.name + ': ' + value + ' %';
});
myTooltip += '<br/><b>Total : ' + total +'</b>'; // Adding total to the tooltip
return myTooltip;
}
},
...
Fiddle
I got what I was looking for using some of what Core972 did. Here it is
tooltip: {
split: true,
formatter:function(){
var myTooltip = '<b>' + this.x + '</b>',
value,
total = [1000, 2000, 3000, 4000, 5000, 6000, 10500];
(this.points).forEach(function(item){
value = ((item.y / total[item.series.data.indexOf( item.point )]) * 100).toFixed(2);
myTooltip += '<br/>' + item.series.name + ': <b>' + value + '%</b>';
});
return myTooltip;
}
},

How to fix bubble size (marker size) in canvasjs?

I want chart to look like this:
So far I'm very close to my expected output but not exactly what I want. Here is my current codebase:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var ToolTipHtml = "";
ToolTipHtml += "<div><b>{number}</b></div>";
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "SEStimate Planning Graph"
},
axisX: {
title: "Age in Months",
interval:1
},
axisY: {
title: "SEstimate Score",
interval:5,
gridThickness: 0
},
creditText: "Hardiks Line Chart",
data: [
{
type: "line",
color:"blue",
markerSize:0,
toolTipContent: "",
lineThickness:2,
dataPoints: [
{ x: 36, y: 35 },
{ x: 45, y: 35}
]
},
{
type: "line",
color:"blue",
toolTipContent: "",
markerSize:0,
lineThickness:2,
dataPoints: [
{ x: 42, y: 0 },
{ x: 42, y: 43}
]
},
{
type: "line",
color:"cyan",
toolTipContent: "",
lineThickness:2,
indexLabelPlacement: "inside",
dataPoints: [
{ x: 43, y: 35},
{ x: 48, y: 37,markerSize:20, indexLabel:"5"},
{x:55,y:42,markerSize:20, indexLabel:"5"}
]
},
{
type: "line",
color:"purple",
toolTipContent: "",
lineThickness:2,
markerSize:27,
dataPoints: [
{ x: 43, y: 35 },
{ x: 48, y: 43,indexLabel:"10"},
{x:55,y:54, indexLabel:"10"},
{x:61,y:60, indexLabel:"10"},
{x:67,y:70, indexLabel:"10"},
]
},
{
type: "line",
color:"red",
toolTipContent: "",
lineThickness:2,
markerSize:0,
lineDashType: "dash",
dataPoints: [
{ x: 41, y: 25 },
{ x: 47, y: 25},
{ x: 61, y: 58},
{ x: 72, y: 58}
]
},
{
type: "line",
color:"green",
toolTipContent: "",
lineThickness:2,
markerSize:0,
lineDashType: "dash",
dataPoints: [
{ x: 40, y: 30, abc:"hardy1" },
{ x: 61, y: 76, abc:"hardy2"},
{ x: 72, y: 76, abc:"hardy3" }
]
},
{
type: "bubble",
toolTipContent: "",
indexLabelPlacement: "inside",
dataPoints: [
{ x: 39, y: 20,z:2.0, number: "II",indexLabel: "II",markerColor: "yellow", radius: "90%" },
{ x: 39, y: 30,z:2.0, number: "HH", indexLabel:"HH",markerColor: "yellow", radius: "90%" },
{ x: 42, y: 35,z:2.0, number: "JJ", indexLabel:"JJ",markerColor: "yellow", radius: "90%"},
{ x: 45, y: 45, z:2.0, number: "GG", indexLabel:"GG",markerColor: "yellow", radius: "90%"},
{ x: 48, y: 50, z:2.0, markerSize:10,number: "EE", indexLabel:"EE",markerColor: "yellow", radius: "90%"},
{ x: 48, y: 35, z:2.0, markerSize:10, number: "FF", indexLabel:"FF",markerColor: "yellow", radius: "90%"},
{ x: 51, y: 43, z:2.0, number: "DD", indexLabel:"DD",markerColor: "yellow", radius: "90%"},
{ x: 52, y: 81, z:2.0, number: "CC", indexLabel:"CC",markerColor: "yellow", radius: "90%"},
{ x: 54, y: 35, z:2.0, number: "BB", indexLabel:"BB",markerColor: "yellow", radius: "90%"},
{ x: 54, y: 70, z:2.0, number: "AA", indexLabel:"AA",markerColor: "yellow", radius: "90%"}
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 450px; width: 100%;">
</div>
</body>
</html>
Output of my code looks like this:
How can I fix all the bubbles size in bubble chart of CanvasJS? Is there any property for setting and fix all the bubbles in same size?
So far I tried markerSize Property and also set all bubbles data's z field value to same but all the bubbles are looking very large. I want to show the bubbles in small size.
Hardik,
You can try scatter chart instead of bubble to achieve this.
Check this jsfiddle for solution for your requirement.
var ToolTipHtml = "";
ToolTipHtml += "<div><b>{number}</b></div>";
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: "SEStimate Planning Graph",
fontSize: 40,
fontColor: "#000",
horizontalAlign: "left"
},
axisX: {
title: "Age in Months",
interval: 1,
minimum: 35.5,
labelFontSize: 14,
labelFontColor: "#000",
titleFontColor: "#000",
titleFontSize: 20,
tickColor: "transparent",
lineColor: "#4A83BA",
},
axisY: {
title: "SEstimate Score",
interval:5,
gridThickness: 0,
labelFontSize: 14,
labelFontSize: 14,
labelFontColor: "#000",
titleFontColor: "#000",
titleFontSize: 20,
tickColor: "transparent",
lineColor: "#4A83BA",
maximum: 100,
},
data: [
{
type: "line",
color:"#4A83BA",
markerSize:0,
toolTipContent: "",
lineThickness:2,
dataPoints: [
{ x: 35, y: 35 },
{ x: 36, y: 35 },
{ x: 45, y: 35}
]
},
{
type: "line",
color:"#4A83BA",
toolTipContent: "",
markerSize:0,
lineThickness:2,
dataPoints: [
{ x: 42, y: 0 },
{ x: 42, y: 43 }
]
},
{
type: "line",
color:"#00B2EC",
lineThickness:2,
markerSize:30,
dataPoints: [
{ x: 43, y: 35 },
{ x: 48, y: 37 },
{ x: 55, y:42 }
]
},
{
type: "scatter",
color:"#00B2EC",
indexLabelPlacement: "inside",
indexLabelFontSize: 16,
indexLabelFontColor: "#fff",
markerSize:30,
markerBorderThickness: 1,
markerBorderColor: "#79A2BF",
dataPoints: [
{ x: 43, y: 35 },
{ x: 48, y: 37, indexLabel:"5" },
{ x: 55, y:42, indexLabel:"5" }
]
},
{
type: "line",
color:"purple",
toolTipContent: "",
lineThickness:2,
markerSize:30,
markerBorderThickness: 1,
markerBorderColor: "#79A2BF",
dataPoints: [
{ x: 43, y: 35 },
{ x: 48, y: 43 },
{ x: 55, y: 54 },
{ x: 61, y: 60 },
{ x: 67, y: 70 },
]
},
{
type: "scatter",
color:"purple",
toolTipContent: "",
indexLabelPlacement: "inside",
indexLabelFontSize: 16,
indexLabelFontColor: "#fff",
markerSize:30,
markerBorderColor: "#79A2BF",
dataPoints: [
{ x: 43, y: 35 },
{ x: 48, y: 43, indexLabel:"10" },
{ x:55, y:54, indexLabel:"10" },
{ x:61, y:60, indexLabel:"10" },
{ x:67, y:70, indexLabel:"10" },
]
},
{
type: "line",
color:"red",
toolTipContent: "",
lineThickness:3,
markerSize:0,
lineDashType: "dash",
dataPoints: [
{ x: 41, y: 25 },
{ x: 47, y: 25 },
{ x: 61, y: 58 },
{ x: 72, y: 58 }
]
},
{
type: "line",
color:"#00F84C",
toolTipContent: "",
lineThickness: 3,
markerSize:0,
lineDashType: "dash",
dataPoints: [
{ x: 40, y: 30, abc:"hardy1" },
{ x: 61, y: 76, abc:"hardy2" },
{ x: 72, y: 76, abc:"hardy3" }
]
},
{
type: "scatter",
toolTipContent: "",
indexLabelPlacement: "inside",
indexLabelFontSize: 14,
indexLabelFontColor:"#1BBDCA",
markerSize: 30,
markerBorderThickness: 1,
markerColor:"#FFFC47",
markerBorderColor: "#79A2BF",
dataPoints: [
{ x: 39, y: 20, number: "II", indexLabel: "II" },
{ x: 39, y: 30, number: "HH", indexLabel: "HH" },
{ x: 42, y: 35, number: "JJ", indexLabel: "JJ" },
{ x: 45, y: 45, number: "GG", indexLabel: "GG" },
{ x: 48, y: 50, number: "EE", indexLabel: "EE" },
{ x: 48, y: 35, number: "FF", indexLabel: "FF" },
{ x: 51, y: 43, number: "DD", indexLabel: "DD" },
{ x: 52, y: 81, number: "CC", indexLabel: "CC" },
{ x: 54, y: 35, number: "BB", indexLabel: "BB" },
{ x: 54, y: 70, number: "AA", indexLabel: "AA" }
]
}
]
});
chart.render();
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 600px; width: 100%;"></div>

angular-chart.js, Chart.js v2 legend customization. How?

In the documentation there is legendCallback and generateLabels and I don't understand the documentation that much. Given my code below. How can I change the legends to make it into one legend per line,have a background and line chart legend should look like a line not a bar or in short how to customize the legend.
JS:
vm.labels = ['2015 - Aug', '2015 - Sept', '2015 - Oct', '2015 - Nov', '2015 - Dec', '2016 - Jan',
'2016 - Feb', '2016 - Mar', '2016 - April', '2016 - May', '2016 - Jun', '2016 - Jul', '2016 - Aug',
];
vm.series = [
'A',
'B',
];
vm.data = [
[14, 12, 17, 24, 29, 17, 23, 10, 16, 20, 33, 5, 8],
[50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50],
];
vm.colors = [
{
backgroundColor: 'rgba(0,104,26,1)',
borderColor: 'rgba(0,104,26,1)',
},
{
backgroundColor: 'rgba(56,80,143,1)',
borderColor: 'rgba(56,80,143,1)',
},
];
vm.options = {
scales: {
xAxes: [
{
ticks: {
callback: function (value) {
var values = value.split(' ');
var date = [values[0], values[2]];
return date;
},
},
},
],
yAxes: [
{
ticks: {
max: 100,
min: 0,
step: 20,
callback: function (value) {
return value + '%';
},
},
},
],
},
// legend
legend: {
display: true,
position: 'bottom',
},
// title
title: {
display: true,
text: 'Chart',
fontSize: 15,
},
// hover
hover: {
mode: 'single',
},
// tooltips
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function (tooltipItems, data) {
var idx = tooltipItems[0].datasetIndex;
var year = tooltipItems[0].xLabel[0];
var month = tooltipItems[0].xLabel[1];
if (idx === 0) {
return year + '-' + month;
} else {
return '';
}
},
label: function (tooltipItems, data) {
var idx = tooltipItems.datasetIndex;
var dataidx = tooltipItems.index;
var seriesValue = data.datasets[idx].label;
var value = data.datasets[idx].data[dataidx];
if (idx === 0) {
return seriesValue + ': ' + value + '%';
} else {
return seriesValue + ' (' + value + '%)';
}
},
},
},
};
vm.datasetOverride = [];
for (var i = 0; i < vm.series.length; i++) {
vm.datasetOverride.push(
{
lineTension: 0,
fill: false,
pointStyle: 'circle',
pointRadius: 0,
pointHoverRadius: 4,
pointHitRadius: 10,
type: 'line',
}
);
}
vm.datasetOverride[1].borderDash = [5, 1];
HTML
<canvas id="line"
class="chart chart-line"
chart-data="vm.data"
chart-labels="vm.labels"
chart-series="vm.series"
chart-options="vm.options"
chart-colors="vm.colors"
chart-dataset-override="vm.datasetOverride"></canvas>
Currently:

Categories

Resources