"Undefined" on my loop trying to fetch object in json file [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Hi guys I'm having trouble in my for loop because there's a word "undefined" on the result of my loop, I'm trying to fetch objects on my json file and my loop works fine, I'm just wondering on how to remove the "undefined" word in my loop? thanks in advance.
here is the output
here is my code
and here is my json file

In your code, show variable before the loop is undefined, you haven't set some value for it, and using it without value. So, JavaScript can not identify the value of the variable and set it as "undefined"

Try this below:
var show = "";
for(var i=0;i<data.length;i++){
var obj = data[i];
show += "<div>"+obj["id"]+" "+obj["fname"]+"</div>"
}
$(".show").html(show)

Initialise your show variable with an empty string like azizbek mentioned.
let show = '';
If you don't want to, then use a condition to ignore it like this:
if (data[i] && data[i].id) {
let obj = data[id];
show += ...
}
Note:
I see that you use var in places that is not needed, inside a for loop or inside a callback. See this post for more info

Related

Javascript JSON Object error but json validator show valid object [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I have a Json object which i get from a API, so i can not change it and need to work with it like it is. I see it have a lot of backlashes but if i put the json string into a json validator i get the info its vallid.
if i use the json object in javascript i also can read it until the last part where i get a error, when you take my json string and you do the following steps, you will see no error message:
let ResponseJson = {"config":{"data":"market-pairs","limit":1,"symbol":"'LTC'","page":0},"usage":{"day":112,"month":262},"data":[{"name":"Litecoin","symbol":"LTC","total_rows":2221,"marketPairs":[{"id":83223,"asset_id":4,"exchange_id":113,"unique_key":"4:citex:LTC:USDT","1d":"{\"volume\":\"196939102.19\",\"volume_base\":\"1119444.67\",\"volume_change\":\"-29686113.31\",\"volume_base_change\":\"-142615.38\",\"price_change\":\"4.71070407\",\"price_quote_change\":\"4.26000000\"}","1d_volume":196939102.19,"1d_trades":null,"30d":"{\"volume\":\"10993069419.34\",\"volume_base\":\"46739211.09\",\"volume_change\":\"-111703700.37\",\"volume_base_change\":\"6038573.46\",\"price_change\":\"-173.96929593\",\"price_quote_change\":\"-174.42000000\"}","30d_volume":10993069419.34,"30d_trades":null,"exchange":"citex","from_symbol":"LTC","to_symbol":"USDT","price":178.270704,"type":"spot","last_updated":1622999998,"name":"Citex","exchange_lunar_id":"citex","pairing_url":"https://trade.citex.co.kr/trade/{{symbol1}}_{{symbol2}}","market_sort":"LTC_USDT","logo":"https://dkhpfm5hits1w.cloudfront.net/exchanges/citex.png"}]}]}
let size=Object.size(ResponseJson.data[0].marketPairs)-1;
console.log(size);
alert(typeof(ResponseJson.data[0].marketPairs[0]));
it will say you its a object and you can read also the size.
But now if i try to read the value from marketPairs:
console.log(ResponseJson.data[0].marketPairs[i].1d_volume);
then i get the error message:
Uncaught SyntaxError: missing ) after argument list
i dont know currently how to slove this, have somebody a idea?
Object.size = function(obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
let ResponseJson = {"config":{"data":"market-pairs","limit":1,"symbol":"'LTC'","page":0},"usage":{"day":112,"month":262},"data":[{"name":"Litecoin","symbol":"LTC","total_rows":2221,"marketPairs":[{"id":83223,"asset_id":4,"exchange_id":113,"unique_key":"4:citex:LTC:USDT","1d":"{\"volume\":\"196939102.19\",\"volume_base\":\"1119444.67\",\"volume_change\":\"-29686113.31\",\"volume_base_change\":\"-142615.38\",\"price_change\":\"4.71070407\",\"price_quote_change\":\"4.26000000\"}","1d_volume":196939102.19,"1d_trades":null,"30d":"{\"volume\":\"10993069419.34\",\"volume_base\":\"46739211.09\",\"volume_change\":\"-111703700.37\",\"volume_base_change\":\"6038573.46\",\"price_change\":\"-173.96929593\",\"price_quote_change\":\"-174.42000000\"}","30d_volume":10993069419.34,"30d_trades":null,"exchange":"citex","from_symbol":"LTC","to_symbol":"USDT","price":178.270704,"type":"spot","last_updated":1622999998,"name":"Citex","exchange_lunar_id":"citex","pairing_url":"https://trade.citex.co.kr/trade/{{symbol1}}_{{symbol2}}","market_sort":"LTC_USDT","logo":"https://dkhpfm5hits1w.cloudfront.net/exchanges/citex.png"}]}]}
let size=Object.size(ResponseJson.data[0].marketPairs)-1;
console.log(size);
alert(typeof(ResponseJson.data[0].marketPairs[0]));
console.log(ResponseJson.data[0].marketPairs[i].1d_volume);
here is the code in a snippet, you can see the error happen there also
When you see an error like that after adding that particular line, then the syntax error is on that line. With that being said, you cannot have variable names in JavaScript start with a number. But, you can still make it work by accessing the object like a map rather than a member variable, by using bracket instead of dot notation syntax:
console.log(ResponseJson.data[0].marketPairs[i]["1d_volume"]);
That should fix your problem.

Object Obect array Json.stringify string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

Using String/Array String as Variable name in JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

JavaScript: Options is Nullor not an object [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
Hi i have written a small javascript function and i m getting the Error as "Options is Null or not an object"
Here is my code:
function ValidateMarks(sender, args) {
var ddlCategory = document.getElementById('ctl00_rightContainer_ContentTable2_ddlCategory').value;
var ddlDisabilityClass = document.getElementById('ctl00_rightContainer_ContentTable2_ddlDisabilityClass').value;
var GraduationPercntage = document.getElementById('ctl00_rightContainer_ContentTable2_txtGraduationPercntage').value;
var objCVValidateMarks = document.getElementById("ctl00_rightContainer_cvValidateMarks");
if ((ddlCategory.options[ddlCategory.selectedIndex].text == "-- Select Category --" || ddlCategory.options[ddlCategory.selectedIndex].text == "UR") && (ddlDisabilityClass.options[ddlDisabilityClass.selectedIndex].text == "No")) {
if (parseFloat(GraduationPercntage) < parseFloat('49.50')) {
objCVValidateMarks.errormessage = 'You are required 49.50% marks in B.Pharmacy to fulfill the eligibility.';
args.IsValid = false;
}
}
else {
if (parseFloat(GraduationPercntage) < parseFloat('44.50')) {
objCVValidateMarks.errormessage = 'You are required 44.50% marks in B.Pharmacy to fulfill the eligibility.';
args.IsValid = false;
}
}
}
When i check the value for ddlcategory it gives me the selected value but ddlCategory.selectedIndex gives me the value as 'undefined' hence i m getting the above mentioned error.
Try changing ddlCategory from
var ddlCategory = document.getElementById('ctl00_rightContainer_ContentTable2_ddlCategory').value;
to
var ddlCategory = document.getElementById('ctl00_rightContainer_ContentTable2_ddlCategory');
Now try getting the value using ddlCategory.value and selected Index using ddlCategory.selectedIndex
A couple of things:
It appears you have hardcoded in clientIDs for components.
Is this the case? If so please consider using either this:
http://msdn.microsoft.com/en-us/library/system.web.ui.clientidmode.aspx , which will allow you (in .NET 4.5, using ClientIDMode="Static") to have sensible never changing clientIDs (but also lets you run the risk of having more than one item with the same ID on the page).
or this:
document.getElementById("<%= MYELEMENT.ClientID %>").
OR if using seperate javascript files then pass in the clientIDs as parameters into your javascript function.
More specifically for your problem it seems that javascript cannot find ddlCategory or ddlDisabilityClass, I would imagine one of these two lines is failing and giving you a null var:
var ddlCategory = document.getElementById('ctl00_rightContainer_ContentTable2_ddlCategory').value;
var ddlDisabilityClass = document.getElementById('ctl00_rightContainer_ContentTable2_ddlDisabilityClass').value;
It is always good to debug javascript with Alerts when this happens, such as Alert('Object was:'+ddlCategory); This will give you a NULL if it's not found, or tell you specifically what that var is set to.
Looking at this again, your specific problem is that you are getting the values of these objects instead of a reference to the objects themselves. Removing .value from the end of your getElementById calls should fix this (as long as your references are valid).

creating DOM nodes from arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Categories

Resources