Variables to define nested objects? [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I have an object and a few variables I'd like nested inside the variable but for some reason I can only ever get the first nest. Anything after that gives me an error stating that it couldn't read because it was undefined:
var date = 10;
var timestamp = 100;
Que[date] = {timestamp:{"test":"test"}};//this returns {10:{"timestamp":{"test":"test"}}}; for some reason
Que[date][timestamp] = {"test":"test"}; //errors saying, cannot read '100' undefined
console.log(Que);
I'm not sure why this is happening and I'd really like to resolve it with simple means. Btw the Que variable is global inside another script and predeterminietly contains {"10":{"24":{"1":"test"}}}; which is likely why the date variable does work but the timestamp variable doesn't. Any suggestions?
EDIT:
date, and timestamp are both declared outside of the object, however i wish to use them as key's inside of the object..
uppon reading the mod suggested post and implementing what it contained, i ended up with another error
Que = {[date]:{[timestamp]:{"test":"test"}}};//this results in an unexpectd token error located at the [ before date

I think there are more questions to be asked based off of your code snippet, but in your example timesheet is not defined, you can reference the key inside your JSON by using
Que[date]["timesheet"]
To access the object inside. The key that you're looking up with the [] notation should be a string.

Related

Use variable to access array results in undefined [duplicate]

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 5 years ago.
I am getting several arrays returned from a GET reponse, which I need to access. Since their names can change based on the request, I have a variable specifing which array to use.
However I always get undefined. See this:
console.log(current); // trips_out_201702
console.log(theResponse.current); // undefined
console.log(theResponse.trips_out_201702); // this works
How can I make theResponse.current work such that it returns what current actually stands for? Why do I get undefined there?
When the property key in an object is a variable you can use the square bracket notation to access that property.
console.log(theResponse[current]);
when acessing with dynamic attribute You should do as
theResponse[current] not theResponse.current
You are trying to get array value using object's way.
You should try this one instant variable['keyName']
Good Luck!

Access object using dynamic object name [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I have an object with some data inside. The first level of data are 2 arrays (body, cause). Each body and cause array have arrays inside of them (date, year).
totals:[{body:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]},
{cause:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]
}]
What I would like to do is access the body/cause array dynamically based on something the user has changed.
This is how I am accessing them now.
totals[isCause].body[isYear].date[filterNumber]);
My issues is body and date are hard coded in there, and I would like to have access to either body/cause date/year. I can't seem to find what these property names are stored as. I tried to set up a var and do something like this
var bodyCause = "body";
Then I tried to pass it back into my retriever statement.
totals[isCause].bodyCause[isYear].date[filterNumber]);
But that fails. So I'm just trying to figure out what that property name is stored as and if I can dynamically set it when I need to retrieve information.
Your attempt was almost correct. You can easyly use var bodyCause = "body"; and access the content dynamically. Instead of this
totals[isCause].bodyCause[isYear].date[filterNumber]);
you should use this
totals[isCause][bodyCause][isYear].date[filterNumber]);
Should fix your problem.

In Java Script Global Variable is not clear [duplicate]

This question already has answers here:
How can I unset a JavaScript variable?
(12 answers)
Closed 7 years ago.
I have declare global variable in java script, i try to clear with following code but it not clear.
As i defined global variable.
var usno;
then before set value i tried following code
delete window.usno;
usno = undefined;
usno=null;
but no success.
Please help on this
Thanks
Basit.
In short, you cannot delete variables defined with var. If you set the variable using window.usno then it can be. See Understanding delete and the answers to How to unset a JavaScript variable? for more details.
Do you really need to delete the variable though? Instead of making a global variable, restrict the scope of your variable to a function so that it will be garbage collected after the scope of the function ends.
Your first solution is the correct one.
delete window.usno;
That deletes the property usno from the global window object. But here is where the confusion lies, when we test it:
window.usno; // -> undefined
So, a deleted or non-existent property returns undefined. Thus, in effect, the following two statements achieve much the same thing:
delete window.usno;
window.usno = undefined;
They are not exactly the same thing. In the second case, the usno property still exists, as you will find if your iterated through all of the properties of window.
Short answer:
delete window.usno;

How to use the JSTL created variables in the JavaScript? [duplicate]

This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 7 years ago.
I am using the DataTables for viewing data in table form. I am sending the data as a list of objects from the backend(JAVA). I need to retrieve the object Ids as a single string on front end and iterate on them.
For that, in iteration of the data I have concatenated the id with a separator, as
<c:set var="tagIds" value="${tag.id},${tagIds}"/>
The id String is created, what I thought - but I cant use in the JavaScript
In Javascript, I declared a variable as follows
var tagIds = ${userId};
this reflects that Syntax error. This assumes that after comma(,) it is a new variable. I am unable to pass that variable.
Also, I tried sending these values as parameter in javascript function call, but resulting in the same error.
saveTags(${userId}); & saveUploadedTags(<c:out value='${userId}'/>);
Result
Error:
SyntaxError: identifier starts immediately after numeric literal
saveTags(4028808241a34ba60141a35049380000)
You have to make sure that the resulting JavaScript code is valid, as you yourself noted:
var tagIds = "${userId}";
Now that's not necessarily the safest thing to do if you're not 100% sure of the contents of the stuff making up the id string. The best thing to do would be to use a JSON encoder; as far as I know there isn't one built into the standard JSTL/EL set of functions, but there are many available on the web.

Using String to get JSON Property [duplicate]

This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

Categories