My object is not recognizing the key that is already been set - javascript

I have this snippet of code (unfortunately it won't work for you unless you have a qualtrics account and go into preview survey and run it in the console) that keeps throwing the error (Cannot set property 'questions0' of undefined). Yet I just added an object named ArrayOfBlocks2 to the main object. Can someone tell my why its saying ArrayOfBlocks2 is undefined?
Qualtrics.SurveyEngine.setEmbeddedData("ArrayOfBlocks",ArrayOfBlocks)
var ArrayOfBlocks1 = Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")
for(i=0;i<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks").length;i++){
for(k=0;k<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements.length;k++){
var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
console.log(ArrayOfBlocks2)
ObjectIDWithQuestions[ArrayOfBlocks2]={}
Qualtrics.SurveyEngine.setEmbeddedData("OBID",ObjectIDWithQuestions);
ObjectIDWithQuestions.ArrayOfBlocks2["questions"+ k]=Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements[k].QuestionID
Qualtrics.SurveyEngine.setEmbeddedData("ObjectIDWithQuestions",ObjectIDWithQuestions)
}
}
I expect it to not throw an error, and to set "questions + k" as a object key.

Embedded data won't store an array by default, you will likely need to json encode the data before storing, and json parse the data on retrieval.

Related

Why am I not seeing the added property in the object?

I have to add a property for an object returned from my db before pushing it to an array. Changing properties work, but adding new ones doesn't. Can anyone can explain the logic behind this behavior?
ids.forEach(async (id, index) => {
//get object without highlight property
let real_a = await database.getA(id)
real_a.highlight = "shoud add highlight property to real_a object"
realItems.push(real_a)
// the correct string is printed
console.log(real_a.highlight)
//object still doesn't have that property
console.log(real_a)
}
It was the intended behavior.Sorry for bothering.
I was using a mongodb query for the database.getA(id) function and it turns out you have to specify a parameter in the mongodb query to get an actual changeable JSON object.
Here is the complete answer:
Why can't you modify the data returned by a Mongoose Query (ex: findById)

Why javascript cannot access some object by key?

I have a JavaScript Object named "userinfo" (it stored some user's info). And I want to access value by key in it. For all the keys I can success get, except one key named "auths". And then I print it in console by console.log(userinfo), it shown as well. And while I traversal it Object, the key don't show again...
And then I click the option "Store as global variable" in Chrome debug console. And not when I try to access, it works well.
Here it's my code and debug's screenshot.
console.log(userinfo);
for (var key in userinfo){
console.log(key + " = " + userinfo[key]);
}
Because here some my really personal informations in it, I produced this picture.(Position I've printed "hide info").
I want to know why the code working not well, and how can I access the info stored in key "auths".
Thanks!
console.log is deceiving. It's printing a "live" object. If object is altered after it's been logged, the log will update (you'll see the new property when you expand the object in the log). Naturally, this doesn't apply to the temp strings you build there with concatenation. So yes, I'd bet 10 bucks that the object does not indeed have auths property at the time of printing. It is added later.
Observe this in action (look in browser's console)
var myobj = { foo: 1 }
console.log(myobj);
myobj.bar = 2;

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Javascript string/object/array confusion with JSON

I'm having a Laravel backend return some errors via Validator. These errors are passed through a HTTP response made by angular, and returned in JSON format.
The object is structured as seen below:
That name object has a value, which is the actual message that I'm after.
Currently, using loops etc., I can only get the name of the array (name) as a string...
I sometimes get multiple arrays within this error object, and I won't always know their names, so how may I retrieve that 0-index value in each of them, in a loop?
Thanks for any help.
Edit #1
Looping through it like this:
for(var err in res.data.errors){
console.log(Object.err[0][0]);
}
Gives me a Cannot get [0] index of undefined
How about this:
let errors = Object.values(response.data.errors);
// errors is now an array of arrays containing the validation errors
errors.forEach( (errorArray) => {
console.log(errorArray[0]);
} );
Another approach would be using Object.keys() instead of values. This is similar to what you already tried, where you get the name of the error property as a string, and then use it to access each error array:
let keys = Object.keys(response.data.errors);
keys.forEach( (errorKey) => {
console.log('error type', errorKey);
let errorArray = response.data.errors[errorKey];
console.log(errorArray[0]);
} );

Checking if an element exists in json

using the following feed:
http://api.twitter.com/1/statuses/user_timeline.json?screen_name=microsoft&include_rts=1&count=10
I am successfully able to loop through this to get the details I want to display on my html page.
However, I need to check if retweeted_status.user.profile_image_url exists, and I am not sure how to do that?
Currently I am looping through the data where data is returned by jquery-ajax:
data[i].retweeted_status.user.profile_image_url
if data[i].retweeted_status.user.profile_image_url does not exist, it does not return null or undefined, I just get the following error:
cannot read property 'user' of undefined
That error message suggests that either your data[i] or your retweeted_status is undefined, which means your call to get the json is most likely failing. WHen data is returned from Twitter it will aways have a profile image url, because they show an egg-like image for those with none uploaded. You should put this before your for loop:
if (typeof(retweeted_status) != "undefined")
{
//code for what to do with json here
}
I think it's a good answer:
if('key' in myObj)
if (something !== undefined) {
...
}
... or even better:
if (typeof something != "undefined") {
...
}
If you are looping and accessing nesting objects:
if(!data)
return;
while(data.length)
{
var tweet_data = data.shift();
/* do some work */
if(!tweet_data|| !tweet_data.retweeted_status)
continue;
var retweeted_status = tweet_data.retweeted_status;
/* do your other work */
}
This loop no longer needs to use array indexes, which isn't the most efficient unless you specifically need the index for something. Instead, it pops the first element off the array and using that object directly. The loop internals can then check the existence of a property on tweet_data.
I try to avoid using more than 1 level of dereferencing for 2 reasons (like objA.child.property):
1) You can check the existence of an object from the start and if it doesn't exist, jump out or assign default values.
2) Everytime JavaScript needs to access the method property, it first has to find child withing objA and then access property. Could be slow in large loops.
Take a look at $.grep(). It helps you loop through JSON objects. I used it on the link you provided. I used it to loop through the tweets and find the retweeted user images. You can have a look at my code here:
http://jsfiddle.net/q5sqU/7/
Another thing you can do, which has worked for me:
if(retweeted_status) {
// your code
}

Categories

Resources