dynamic object properties javascript - javascript

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
};

Related

Add items to a Javascript 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;
}
};

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

Add existing variable to array in javascript

I've got this HTML
<div class="calListChip" id="label-bDd1aDFjNnQ2aHFxOTN2cGQyM2JhaXA2cmtAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ" title="Testkalender1">
<div class="calListChip" id="label-OWFmbmdwbWprbTRxMmFrOTNycGlicmM2bjBAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ" title="Testkalender2">
and I've got this code, creating variables with the title of a html div as name and then I pass the label of the html object as parameter to the variable.
var elements = document.body.getElementsByClassName('calListChip');
var view1 = [];
//For each element found
for (var i = 0; i < elements.length; i++) {
//Variable names cant inlude spaces
var title = elements[i].title;
title = title.replace(/ +/g, "");
//create the variable
window[title] = elements[i].id;
//if 'test' exist in the title, add the variable to an array
if (elements[i].title.toLowerCase().indexOf("test") >= 0)
{
view1.push(window[title]);
}
};
But the view1 array dosent get the variable reference but instead a string with the title name, that I cant use later on.
This is the result I want
view1 : [Testkalender1, Testkalender2]
This is the result i get
view1 : ["Testkalender1", "Testkalender2"]
The problem is that i dont know how many or the title/label of the html elements so i need to dynamically create variables and then by a keyword in the title put them in the right array
Any suggestions?
It is not clear how exactly you want to generate your desired result (e.g. where the data comes from), but I can help explain what is happening with your current code. When you do this:
window[title] = elements[i].id;
You are creating a global variable of name title and assigning it the string value located in elements[i].id. So, now you have a global variable with a string in it.
When you later do this:
view1.push(window[title])
You are just pushing a copy of that string in the view1 array. That string has nothing to do with your global variable. So, view1 will end up being an array of strings.
If you want view1 to end up being an array of objects like your example here:
view1[0] = {
name: 'TestKalendrar',
items: [Testkalender1, Testkalender2]
};
Then, you have to push objects into the array, not strings.
I should add that I have no idea what your creation of global variables with this line:
window[title] = elements[i].id;
is doing to help you with your problem in any way. It should not be necessary.
I'd be happy to help you get a different result, but so far you've shown a desired array of objects, but not shown us where you get the name property from or the items property. If you can edit your question to show where those values come from, we can help with a solution to generate that.
I reworked your code a little and indeed the variables are being created see the fiddle at http://jsfiddle.net/smylydon/Q5m6Q/
var elements = document.body.getElementsByClassName('calListChip');
var view1 = [];
//For each element found
for (var i = 0, length = elements.length; i < length; i++) {
//Variable names cant inlude spaces
var title = elements[i].title;
title = title.replace(/ +/g, "");
//create the variable
window[title] = elements[i].id;
//if 'test' exist in the title, add the variable to an array
if (title.toLowerCase().indexOf("test") >= 0) {
view1.push(window[title]);
console.log('variable:', window[title]);
}
};
console.log('view1:', view1);

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

Categories

Resources