javascript add one object to be a member of another [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a Javascript object that I use for global variables, username, userid, etc.. I call it myGlobals. I have a need to load another object via jQuery (application preferences) that I will also need to access globally. For cleanliness, I want it to be a part of myGlobals.
I see posts on how to "merge" the two objects, or add the second one as an array, but that is not exactly what I want. I have this:
var appPref = JSON.parse(xhr.responseText); //this works fine
myGlobals.appPref = appPref; // this does not
I want to be able to do something like this:
alert(myGlobals.appPref.messages.hello);
but I am getting a "myGlobals.appPref: is undefined.
How do I do this? I am using jQuery if there is some magic in there that I could use.

myGlobals.appPref = appPref;
This is how you do it.
The problem is somewhere else. Try to put a console.log(appPref); before this line. Most likely it will show undefined.

Related

Do I have to address JavaScript function variables in order? How to do it? [duplicate]

This question already has answers here:
Skip arguments in a JavaScript function
(9 answers)
Closed 9 months ago.
How do I send one or more variables in a JavaScript function without sending null values to unused arguments?
I have a function:
function setProjectParameters(trigger, pp_ts, pp_t, pp_bs, pp_dg, pp_ll){alert("the rest of the code is here doing something");}
Sometimes I want to call this function and only send a value to pp_bs, now I do it like this:
setProjectParameters(null,null,null,"8");
Can I do it something like this?: (It doesn't work so I guess not...)
setProjectParameters(pp_ts="44");
What is the proper way to do it?
The easiest I think is to have the parameters in the function as an object and have defaults for them if you need to. Then you can target a specific parameter.
function setProjectParameters({trigger = 'if you need defaults add them like this', pp_ts, pp_t, pp_bs, pp_dg, pp_ll}){alert("the rest of the code is here doing something");}
Then use the function like this
setProjectParameters({pp_ts="44"});

Unable to access an array where the contents of said array are visible in Console.Log [duplicate]

This question already has answers here:
How can I make console.log show the current state of an object?
(12 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I setup a global variable to hold the data array:
var data = [];
This is a global variable as it is used outside of a function and needs to be accessible for all functions
I then iterate over a data set and populate the data array.
When I access this array using the console:
console.log(window.data);
I can see the following in Chromes console view:
There are many more records in the data set, they all follow exactly the same format
The issue I am having is, I cannot access this data array and am seeing zero length as shown below:.
console.log(window.data.length); // returns 0
I'm not clear on why this is occurring and am hoping someone can point out what I am doing wrong.
It seems like the result of processing this array is not available at the time I am trying to get the length, therefore I am getting zero.
Have tried the following at the end of the html file:
$( document ).ready(function() {
console.log("ready!"); // returns ready!
console.log(window.data[15]); // returns undefined
});
Not quite sure how to proceed, so any advice would be very welcome.
EDIT:
This was resolved by the use of promises (bottom link in the duplicate notice above).
Previous code was removed as it didn't add to the discussion and would probably only create confusion
Core issue was based on data not being available on page load due to processing of large arrays.

change key names of JSON using array [duplicate]

This question already has answers here:
JavaScript: Object Rename Key
(35 answers)
Closed 6 years ago.
Say I have some JSON data like this:
blah = [
{"Species":"setosa","Sepal.Length":5.1,"Sepal.Width":3.5},{"Species":"setosa","Sepal.Length":4.9,"Sepal.Width":3}
]
In my code, I won't necessarily know the key names of the JSON. Therefore, I can grab the keys like this (I do know that all elements of the array are identical in their keys):
mynames = Object.keys(blah[0]); // gives this... ["Species", "Sepal.Length", "Sepal.Width"]
I am able to change the name of the first key called Species here to newthing like this:
JSON.parse(JSON.stringify(blah).split('"Species":').join('"newthing":'));
But if I didn't know it was called 'Species', but knew it was the first element of 'mynames', I thought I could do the same thing like this:
JSON.parse(JSON.stringify(blah).split('mynames[0]:').join('"newthing":'));
or
JSON.parse(JSON.stringify(blah).split('"mynames[0]":').join('"newthing":'));
but both fail. Is there a way of doing this simply?
It seems what you want is
blah[0].newthing = blah[0][mynames[0]];
delete blah[0][mynames[0]];
but knew it was the first element of 'mynames',
Note that the order of keys is not guaranteed, so that might not work in every environment or even for multiple runs.
How do I remove a property from a JavaScript object? explains how the delete keyword can be used to remove properties. You can simply set the new property to the value of the old, then delete the old.

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.

Call function programmatically/"by string" in coffeescript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic object property name
I have a function that I need to call based on a user inputted data.
So for example, I have:
models.cat
models.dog
Now, I want to be able to call models.[my_str] where my_str = "snake". So the computer would think it is trying to execute models.snake. Is there a way to do this in javascript or better yet coffeescript?
You should be able to call it like so:
models[my_str]();
This should work in both Javascript and Coffeescript.

Categories