How to add a new item to struct in JavaScript? - javascript

I have a struct in JavaScript
settings = {
"type-1": {
"setting-1": true,
"setting-2": 2
}
"type-2": {
"setting-3": "value",
}
};
I can modify the items:
settings["type-1"]["setting-1"] = false;
But how can I add a new item in this struct?
Trying
settings["type-new"]["setting-100"] = "new one";
But settings["type-new"] is undefined. So how to add a new one?

you can do it on one line:
settings["type-new"] = {"setting-100": "new one"}

You need to set settings["type-new"] to an object first.
settings["type-new"] = {};
settings["type-new"]["setting-100"] = "new one";

Dogbert got it right, since you're using object literals (that's what they're called, not structs :P), you have to create them, before you can assign values to them. Doing settings["type-new"]["setting-100"] = "new one"; is equivalent to undefined["setting-100"] = "new one";. That's why it doesn't work.
On the side, you're really better off not using dashes in your keys, I find it easier to write code like yours along the lines of:
settings.typeNew.setting100 = "new one";
Which is more intuitive (the [""] notation is very serviceable in cases where the property name is the value of a variable, and you -rightly so- don't want to use eval).

Related

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Assign variable value as variable name

the problem is i want to shorten my code by calling a variable using other variable's value
long working version:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})
it will get the id of mouseovered then check if it matched one of the variable by using switch
what i want to obtain is something like this:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
of course the above code wouldn't work but is there a workaround for this?
UPDATE: Arun's answer worked and ill accept it soon and as for the comments requesting for the full code, here's a chunk of it after i applied Arun's
var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}
$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})
function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}
it will be used for a world map, feel free to make any suggestions for making it more dynamic
You can store the country info in an object like a key value pair, then use bracket notation to access it dynamically
var countries = {
russia: new Array('-15px'),
switzerland: new Array('-5px')
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id][0])
})
If you don't have multiple values then
var countries = {
russia: '-15px',
switzerland: '-5px'
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id])
})
try using eval() function
var russia = new Array('-15px')
var switzerland = new Array('-5px')
$('.country').mouseover(function(){
active_country_lift(this.id,eval(this.id)[0])
})

combining text into a variable name in javascript

i have looked for an answer to this, but im also not sure im using the correct wording to give me a good search result. So without further adoo.
I am trying to make a random name generator in JavaScript, and I don't want a 300 line switch if it can be avoided. No Jquery if it can be avoided, mainly as i want to learn how to code in JS, for no other reason than that. But if i have to use Jquery, so be it. Learning and all.
The idea is that the script will take the race, gender, then randomly select the first name, surname and proffesion from an array. I can get this to work in IF statements and switches. But I want to try it on as little code as possible. The example below is for humans, but the idea is to pretty much use any fantasy race... dwarves, elves... yes its for dungeons and dragons. Maybe later on use JSON for the array data, but that's later.
var HumanFemale = ["Diane","Laura","Amy"];
var HumanMale = ["Steve","Dave","Tony"];
var HumanS = ["Druss","Hale","Taylor"];
var Proff = ["Theif","Mercenary","Soldier"];
function chargen(race,gender){
var x = race.concat(gender);
var xs= race.concat('S');
document.getElementById("OutputR").innerHTML= race;
document.getElementById("OutputG").innerHTML= gender;
document.getElementById("OutputF").innerHTML= x[Math.floor(Math.random()*x.length)];
document.getElementById("OutputS").innerHTML=xs[Math.floor(Math.random()*xs.length)];
document.getElementById("OutputJ").innerHTML=Proff[Math.floor(Math.random()*Proff.length)];
}
Maybe I need dynamic variables, but i'm not sure how to convert text into a var name.
Thanks
I think an object probably makes your life a little easier, but the idea is generally the same as what you appear to have.
In JavaScript you can reference a property of an object like an array. This means that if you have a property name that can be variable, you can use the array convention to fetch the property instead of the "." convention.
Here's an example:
var example = {
"first": "hello",
"second": "world"
}
//Using dot-notation
alert(example.first); //alerts "hello"
alert(example.second) //alerts "world"
//Using array-notation
alert(example["first"]); //alerts "hello"
alert(example["second"]); //alerts "world"
Now, if the property we want is variable, we can't use the dot-notation, but we can use the array-notation:
var prop_name = "second";
//Using dot-notation
alert(example.prop_name); //throws an error (undefined property)
//Using array-notation
alert(example[prop_name]); //alerts "world"
So, if you create essentially a dictionary object, you may find it's easier/more concise to complete your task:
var dict = {
"Human": {
"Male": ["Steve", "Dave", "Tony"],
"Female": ["Diane", "Laura", "Amy"],
"Surname": ["Druss", "Hale", "Taylor"]
},
"Elf": {
"Male": [/* names */],
"Female": [/* names */],
"Surname": [/*names */]
}
}
function rand_attributes(race, gender) {
var first_name_index = Math.floor(Math.random() * dict[race][gender].length),
last_name_index = Math.floor(Math.random() * dict[race]["Surname"].length),
first_name = dict[race][gender][first_name_index],
last_name = dict[race]["Surname"][last_name_index];
//Now first_name and last_name each contain random values
//Do what you need to with those values from here
}
That code is untested, but it should at least conceptually work out.
Here's what I crudely chucked together.
var Proff=["Theif","Mercenary","Soldier"];
var CharacterName={};
CharacterName['human']={};
CharacterName['human']['female'] = new Array('Diane','Laura','Amy');
CharacterName['human']['male'] = new Array('Steve','Dave','Tony');
CharacterName['human']['surname'] = new Array('Druss','Hale','Taylor');
//just add more stuff here!
document.getElementById('OutputR').innerHTML= 'boo';
function chargen(race,gender){
document.getElementById('OutputR').innerHTML= race;
document.getElementById('OutputG').innerHTML= gender;
document.getElementById('OutputF').innerHTML= grabrandom(CharacterName[race][gender]);
document.getElementById('OutputS').innerHTML= grabrandom(CharacterName[race]['surname']);
document.getElementById('OutputJ').innerHTML= grabrandom(Proff);
}
function grabrandom(arrayofvalues){
return arrayofvalues[Math.floor(Math.random()*arrayofvalues.length)];
}
chargen('human','female');
It's nothing special and a couple of bits could be sharpened, but it's functional and gives you the idea on how it could be done.
The solution i got, heavily based on xjstratedgebx's responce.
var names = {
"Human": {
"Female": ["Diane","Laura","Amy"],
"Male": ["Steve","Dave","Tony"],
"Surname": ["Hall","Young","Taylor"]
}
}
function namegen(race,gender){
var firstname = names[race][gender][Math.floor(Math.random() * names[race][gender].length)];
var lastname = names[race]["Surname"][Math.floor(Math.random() * names[race]["Surname"].length)];
document.getElementById("OutputR").innerHTML= "Human";
document.getElementById("OutputG").innerHTML= "Female";
document.getElementById("OutputF").innerHTML= firstname;
document.getElementById("OutputS").innerHTML= lastname;
}

Javascript object from string property and values

Is it possible to create a property based on string values.
I have a Json object, which used to fill the UI (select box).
"Conf" :{
"Color":[
{
"Value":"BLUE"
},
{
"Value":"GOLD"
}
],
"Size":[
{
"Value":"12"
},
{
"Value":"11"
}
],
}
Based on the selection, I need to add it to an object (Item.Conf below).
addSel provides the selection type (Color, Size etc), and the value (BLUE, 11 etc).
How can I add the selection as shown below.
So if the choice is Color : BLUE, I need to add it as Item.Conf[0].Color.Value = "BLUE"
Is it possible?
Item = {
Conf: [],
addSel: function(type, val){ //for example type="Size", val = "11"
//.... need to selection to Conf
// add a member "Size" from type string
//set its value as val
console.log(Conf[0].Size.Value) //=> 11
}
}
In essence is it possible to make an object like
"Size":{
"Value": 11
}
from strings
Your question is not entirely clear for what exactly you're trying to do, but perhaps you just need to know about using the [variable] syntax to address a property name using a string.
Example:
var x = {};
var propName = "Value";
x[propName] = 11;
This is equivalent to:
var x = {};
x.Value = 11;
But, the first form allows the property name to be a string in a variable that is not known at the time you write the code whereas the second form can only be used when the property name is known ahead of time.

Set value to non existing object

Say i have this object:
test = {
testObj: {
"1": {
"key": "value"
}
}
}
And i want to add values to testObj like so:
test.testObj["2"].key = "my value";
I get error TypeError: Cannot set property 'key' of undefined
Now i do understand that key does not exist yet, but 2 doesn't exist also, and yet i can set value to it:
test.testObj["2"] = "something";
So what can i do about it?
EDIT
wow i feel stupid for not figuring that out by myself... anyways thank you guys.
Javascript doesn't know what test.testObj["2"] should be in this scenario, so it ends up testing it as an existing property:
test.testObj["2"].key = "my value";
The assignment can only apply to the last part of the structure on the left.
But you can tell it what it is by creating the object first:
test.testObj["2"]={};
test.testObj["2"].key = "my value";
Or in a single step:
test.testObj["2"] = { key: "my value"};

Categories

Resources