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;
}
};
Related
I like to create an object using javascript/node.js with dash in the middle of the key's name.
Here is an array that I am using today that need to convert to an object.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;
How to create an object with key like this val-name?
I've got a few spare minutes. So, code-review hat goes on.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;
Firstly, I think you have some typographic errors in this code. The last two values have oddly paired quotes.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';
Next, at the moment, you're assigning keys to an array. Which probably isn't what you mean (summary of the issue here; short version is that some collection methods will give you unexpected results). You likely mean to start an empty object as data.
var data = {};
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';
Finally, you can use data literals in JS, rather than serial assignment.
var data = {
'__type': 'urn:inin.com:connection:icAuthConnectionRequestSettings',
'applicationName': 'test',
'userID': 'blah',
'password': 'blah',
'val-name': 'blah'
}
As part of this, you've created an object with a slot name that has a - in it. There's nothing illegal about this, but it does prevent you from accessing that slot with dot notation.
console> data['val-name']
'blah'
console> data.val-name
NaN
That has nothing to do with the key being illegal, and everything to do with the access being parsed as a subtraction. That is, data.val-name gets interpreted as "Subtract the value of name from the value of data.val" rather than "Access the slot val-name of the object data".
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 currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );
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]];
}
I'm trying to create a for loop that does the exact same thing as this code (quests is an array):
Quest0.text = quests[0]
Quest1.text = quests[1]
Quest2.text = quests[2]
Quest3.text = quests[3]
Quest4.text = quests[4]
Quest5.text = quests[5]
Quest6.text = quests[6]
Quest7.text = quests[7]
Quest8.text = quests[8]
Quest9.text = quests[9]
Quest10.text = quests[10]
Quest11.text = quests[11]
Quest12.text = quests[12]
Quest13.text = quests[13]
Quest14.text = quests[14]
Quest15.text = quests[15]
So far all I've got is this (activeQuests is the length of the array quests):
var q = 0;
for (q=0; q <= activeQuests; q++) {
Quest0.text = quests[q]
}
But I don't know how to get it to do the rest.
You could use eval but you probably shouldn't. You should probably rethink your approach if you have such obviously array-like data that you are manipulating manually element by element.
Check out this blog post from Marco van Hylckama Vlieg: "Variable Variables in Javascript". Relevant snippet:
...using the fact that all global variables are held in the window
array.
var i=1;
window['name' + i] = 'Marco';
document.write('got ' + name1);
There we go! Nice, clean and no eval() necessary."
We'd need to know more to give you exact code, but in order to address a variable by string, it needs to be a property of an object. For example
window.example = 'hello world';
alert(window['example']);
So it really depends on what your QuestN variables are. Are they id's of <input> elements? Are they global variables? Are they defined in local scope with the var keyword?
If you can change how Quest.. are defined then define them as an array so you can do:
Quest[q].text = quests[q];
if you can't then temporarily create an array of Quest.. objects:
var QUESTS = [];
QUESTS[0] = Quest0;
QUESTS[1] = Quest1;
QUESTS[2] = Quest2;
QUESTS[3] = Quest3;
QUESTS[4] = Quest4;
QUESTS[5] = Quest5;
QUESTS[6] = Quest6;
QUESTS[7] = Quest7;
QUESTS[8] = Quest8;
QUESTS[9] = Quest9;
QUESTS[10] = Quest10;
QUESTS[11] = Quest11;
QUESTS[12] = Quest12;
QUESTS[13] = Quest13;
QUESTS[14] = Quest14;
QUESTS[15] = Quest15;
Then you can do:
for (var q=0; q<=activeQuests; q++) {
QUESTS[q].text = quests[q]
}
Obviously this is an uglier solution but much better than eval IMHO.
I think you are better off keeping the "quests" array than defining a different variable to each index.
However if you want to loop try eval("Quest" + q + ".text = quests[q]") in the loop.