Dynamically adding members to a javascript object - javascript

I'm working on a scoring script for contract bridge, just for giggles. I'm storing the game as an object:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
}
function deal(bid){
console.log("The bid was " + bid);
game.hand = {"bid" : bid , "made" : undefined};
score();
}
So what I'd like to do though, better than this, is to keep a history of the games played this session. I'd like to, in pseudocode, do something like this:
game.(hand + (hand.length+1))
or something kind of like that; basically auto-increment a certain object within an object. I'm not so sure an array would would here, but perhaps? I'm open to suggestions/bettering of my code.
PS - I'd prefer to do this in javascript, not jQuery, Prototype, Dojo, MooTools... or any other library. Thanks!
EDIT
Sorry, let me clarify: The result after playing 3 hands or so would be an object like this:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
hand1 : { bid : 2 , made : 2 } ,
hand2 : { bid : 1 , made : 4 } ,
hand3 : { bid : 3 , made : 1 } ,
hand4 : { bid : 2 , //and made hasn't been set yet because we're mid-hand
}

Given your pseudocode, you can do the following:
game[hand + (hand.length+1)]
i.e. game["prop"] == game.prop - both provide access to the same property.

Old question, I see but I have a need to do something similar. I'd vote up the answer but I'm not allowed.
It appears the fastest way to do this is to access the object like a hash / associative array.
var d = {};
var z = "hand";
d[z+1] = "foo";
console.log(d.hand1);
Test this out in firebug. Seems to work pretty well.
JS does not seem to have an php equivalent to force resolution of the variables as in the curley braces around an expression.
d->{z+1} = "foo"; // can't find anything like this in JS.
Hope that helps,

Related

Make the hash value unique in javascript?

For example I am having the hash
var sample={};
sample["test"] = [];
sample["test"].push({name: "test"});
sample["test"].push({name: "test"});
The sample hash should only contain unique values.
Yes i got the solution for that
var sample = [{ id : 1, name : 'Name' }, { id : 1, name : 'Name' }];
var obj = { id : 1, name : 'Name' };
var sample = [obj, obj];
uniq(sample)
Hej man it isn’t possible to got another hash value from 2 same value’s.
For simplify a hash operation is likely like plus so you got 1 + 2 = 3.
It is not that easy but I hope you got he point.

JS - add multiple dict values into a dict key

I have a dictionary as as shown below. I am trying to add dict values into them. This is what it stars with
var animals = {
flying : {},
underground : {},
aquatic : {},
desert : {}
};
For example: If I wanted to add d = {dove : [<some list>] } into animal[flying], how would i do it? I cannot enter the values manually as thus i am running a loop, I am able to write it manually, but not with program.
I have tried animals[flying] = d, this would work for the first time, but when i try to add another value it would be replaced and not appended.
In the end I am looking for something like this: This is what it ends with
var animals = {
flying : {
dove : [<list>],
sparrow : [<list>],
},
underground : {
rabbits : [<list>],
squirrel : [Squirrel],
},
aquatic : {
dolphin : [<list>],
whale : [Squirrel],
},
desert : {
camel : [<list>],
antelope : [<list>],
},
};
well because
myDict[subcat] = x
assigns it. You're working with lists. Think about it - when have you ever added an item to a list this way? Of course that overwrites your previous entry. What you want instead is to push the variable into the array (also, this isn't python. Lists are called Arrays and Dictionaries are called Objects. There is a distinction, but that's beyond the scope of an answer here. Google it).
So do this:
myDict = {
subCat: [],
}
And then when you loop:
myDict[subCat].push(x)
I think what you want to do is:
animals["flying"] = Object.assign(animals["flying"], d);
E.g.
animals = {
flying: {}
}
d = { dove: [1, 2, 3] }
Object.assign(animals["flying"], d);
d = { sparrow: [1, 2, 3] }
Object.assign(animals["flying"], d);
console.log(animals); //{"flying":{"dove":[1,2,3],"sparrow":[1,2,3]}}
var newAnimal = {name: 'bird'};
if(animals['flying']['dove'] && animals['flying']['dove'].length > 0) {
//List already exists so add the new animal
//TODO also check if the animal is already in the list?
animals['flying']['dove'].push(newAnimal);
}else {
//Create the new list
animals['flying']['dove'] = [newAnimal];
}

How can I dynamically build Functions in javascript

Firstly, I am new to javascript.
I am trying to build a webpage to keep track of some numbers for a game.
The game involves keeping track of statistics for a character, in two sections. 1) Base Statistics (Strength, Dexterity ...) and 2) Skills (Drive car, sword, electronics repair, painting ...)
I have a PHP script to call the Stats, with input boxes to adjust them, and a JavaScript code to add them up as they are altered. This works fine for the 8 Stats, but I have written a separate function for each (getStrength, getDexterity ...), with a getTotal function that sums them and displays.
I would like to use a similar process for the 150 Skills (~10 categories with ~15 skills each), without writing 150 separate functions (getDrive, get sword, get painting ...)
I can pull the Skill List from database. Can I run a loop over this to create the required functions?
This is how I would code such things. There's downsides to this approach as well (it doesn't minify well and such), but at least you don't have to define 200 functions that all do the same thing: return a property of your character:
var Charcter = function Character( name ) {
this.id = {
'name' : name,
'class' : 'ranger',
'level' : 1
}
this.stats = {
'str' : 10,
'dex' : 18,
'con' : 14,
'int' : 10,
'wis' : 16,
'cha' : 16
};
this.skills = [
'archery',
'horsemanship'
];
};
Character.prototype = {
'get' : function get( subType, fieldName ) {
return this[subType][fieldName];
}
};
var shilly = new Character('shilly');
console.log('I am a ' + shilly.get('id', 'class') + ' of level ' + shilly.get('id', 'level') );
console.log('My second skill is ' + shilly.get('skills', 1) + '.' );

Count down values of key in Javascript

As said in the title, I need to add the values of my keys.
Here is what I'm doing :
var repeat=ListeInterv[interv].week_data[numsemaine][intensit];
for (var i=0;i<repeat;i++)
{tabpush.push(intensit);}
console.log(tabpush);
For instance (Cardio is intensit):
{ Cardio : 3,
}
I would have in my array :
[Cardio,Cardio,Cardio]
Then I'll use array.lengh, but I don't think this the best option...
I do this because I don't know how to count down the positive values :
{ sport1: 2,
sport2 : -1,
sport3 : 1,
}
Answer I would like (in both cases) is :
3
The Array method will be very long (I have a huge amount of data), my method is in an "if" for positive values.
Any tips ?

Current object property as value in same object different property

Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.
So, when declaring a new object, I'm looking to calculate the giga value:
var myObject = {
super : 1,
mega : 5,
uber : 100,
giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};
But this doesn't work, so, any ways of doing this while declaring, or not possible?
Hope I've made myself clear and thanks in advance!
In Javascript 1.5 you can use the get keyword to define a getter
var obj = {
super : 1,
mega : 5,
uber : 100,
get giga() {
return this.super + this.mega + this.uber;
}
};
alert(obj.giga) // 106
more on this http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/
I assume you have a really good reason for the need to do this inline, otherwise such
trickery is not really a good idea.
Here is what I came up with:
var myObject = (function(){
this.giga = this.super + this.mega + this.uber;
return this;
}).call({
super : 1,
mega : 5,
uber : 100
});
var myObject = {
super : 1,
mega : 5,
uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;

Categories

Resources