How do you make the following JS variable references:
When you have an array (x[0], x[1], ...), and you have a button like so:
<button onclick="say(0)"></button>
The function looks like this:
function say(src){
// Define the box (some random div element will do)
var box = document.querySelector('#box');
// This is wrong, I know... I need to refer to the variable 'response[0]' in this case...
box.innerHTML = response[src];
}
When you have the following list of variables:
var book = "Some Book";
var shelf = "Some Shelf"
var bookshelf = "The cake!"
In this case, if I want to (for whatever reason) refer to the variable bookshelf, how do I do it by combining the variable names of the other two variables?
I mean, I can't do var x = book + shelf; since that will give me the result = "Some BookSome Shelf".
Don't make them variables, make them properties of an object:
var tags = {
book: 'Some book',
shelf: 'Some shelf',
bookshelf: 'The Cake!'
};
var which = 'bookshelf';
var x = tags[which];
You'll probably want to make them properties of an object (although they're probably already properties of the window object):
var stuff = {
book: "Some book!",
shelf: "Some shelf",
bookshelf: "The cake!"
};
function say(src) {
// Define the box (some random div element will do)
var box = document.querySelector('#box');
box.innerHTML = stuff[response[src]];
}
Related
I have a variable with some object/properties and I need to add a trademark to one of them. Is this possible?
var something = {
name: "This is trademarked",
//some more objects
};
I tried applying it this way:
var trademark = document.write("\u2122");
var something = {
name: "This is trademarked" + trademark,
//some more objects
};
But shows as undefined.
var something = {
name: "This is trademarked",
//some more objects
};
var trademark = "\u2122";
something.name += trademark;
// this is just to show the result, don't used it in a real case
document.write(something.name)
Eduardo's solution got me to the solution that worked for me in case anyone else views this in the future.
var trademark = "\u2122";
var something {
name: "some text " + trademark,
//more object
}
My app is hitting a WebAPI that returns some JSON records. I get them via jQuery AJAX and assign the JSON to a JavaScript variable. I can loop through and make changes to existing items without issue. However, how do I add more "records" to this object? I'm trying to understand the structure of the resulting variable.
Here is what I have as a test. Is this the best way?
var trustAccounts = {"accounts":[
{"entityId":12345,
"type":"IOLTA",
"nameOnAccount":"Sam Smith Trust",
"accountNumber":"987654",
"bankCode":"003",
"bankName":"Bank of Stuff",
"accountDate":"12/15/2014",
"status":"A",
"exempt":"N",
"accountId":142922,
"action":"U"}]};
var newaccount = {};
newaccount.entityId = 23456;
newaccount.type = "IOLTA";
newaccount.nameOnAccount = "John Smith Trust";
newaccount.accountNumber = "789456";
newaccount.bankCode = "003";
newaccount.bankName = "Bank of Stuff";
newaccount.accountDate = "12/15/2014";
newaccount.status = "A";
newaccount.exempt = "N";
newaccount.accountId = 142923;
newaccount.action = "U";
trustAccounts.accounts.push(newaccount);
console.log(trustAccounts);
So if we name the returned variable object we can simply create new elements using object.newItemName. Eg below:
object.newItemName = 'Hello World'
You just add them, as if they already existed. A JSON-parsed object is just a normal JavaScript object.
let obj = {};
obj.newProp = 5;
console.log(obj.newProp); // 5
obj['newProp'] = 4;
console.log(obj.newProp); // 4
You can set them in two ways, with the dot-notation or with square brackets ([]). The dot-notation way, the value after the dot is what it's called. The square bracket can accept a string or variable, so you can use it to set a property to a specific name.
If you need to nest things, you have to create each level. For example, if you wanted to set obj.something.aValue, you could do something like this:
let obj = {};
obj.something = {};
obj.something.aValue = 5;
Or, you can also do it in fewer shots, depending what you're doing:
let obj = {
something: {
aValue = 5;
}
};
In jQuery, I can add multiple attributes to an element like so...
var input = $('<input/>').attr({ type : 'text', value : 'New Value'});
My question is, how can I achieve this using a variable like this...
var input = $('<input/>').attr(inputAttr);
I was under the assumption that inputAttr should be an object and that I could add to that object. I must be mistaken. This was one of my many attempts to make this happen.
var inputAttr = {};
inputAttr.add({ type: 'text' });
inputAttr.add({ value : 'New Value' });
I also tried like this....
var inputAttr = {};
inputAttr.add('type: text');
inputAttr.add('value : New Value');
I thought maybe inputAttr should be an array instead, which seems to output a correct string but not sure how to make it an object (which I think it should be).
var inputAttr = [];
inputAttr.push('type: text');
inputAttr.push('value : New Value');
// Then added object brackets like so
var input = $('<input/>').attr({inputAttr});
Any help would be appreciated!
Thank you in advance!
Object properties are just accessed by name. It is not an array.
var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';
var input = $('<input/>').attr(inputAttr);
If you want to access them indirectly via keys it is like a dictionary:
var inputAttr = {};
inputAttr["type"] = 'text';
inputAttr["value"] = 'New Value';
Key-value for object can be set in this way:
var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';
Fiddle.
Having issues with this code block:
var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');
name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);
If I take out the .val on both lines, the code works. I'm trying to dynamically create the "
nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.
Thanks for any help
When trying to assign
nutrients[name].val = tds[1].innerHTML;
the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use
nutrients[name] = {
val: tds[1].innerHTML
};
I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...