I'm trying to create a multidimensional arrays in JS like this:
On my app.js file I have this
var equipValue = new Array();
var selectedTrucks = new Array();
In my function.js file instead I have:
for (var i in selectedTrucks) {
(function(i){
// Simple Ajax request that return me a Json values
var ajaxUrl = '/ajaxRequest/getSingleTruckPosition/' + selectedTrucks[i];
$.ajax({
url: ajaxUrl,
})
.done(function(data) {
if(data != null){
// equipValue doens't go.
// Unable to set property '0' of undefined or null reference
equipValue[i] = jQuery.parseJSON(data);
}
});
Why I obtain: Unable to set property '0' of undefined or null reference ?
Why that variables doens't work on my function.js file but selectedTrucks work perfectly?
Thanks guy
EDIT
Doing some test I've tried this:
equipValue = jQuery.parseJSON(data);
So, the problem isn't scoope but create multidimensional array on Runtime? Or similar?
** EDIT 2**
Here the problem:
var selectedTrucks = new Array();
// other 15 lines of codes and then this:
if(selectedTrucks === undefined || selectedTrucks.length == 0){
cleanMapMarkers();
}
Why cleanMapMakers() is always launched even when selectedTrucks is empty?? All problems that I've found is here.
Thanks
Update : seems equipValue is changed, or overwritten to a different type, somewhere else.
In your code, maybe you're looking for, if selectedTrucks is undefined OR if it's not empty
if(selectedTrucks === undefined || selectedTrucks.length != 0){
cleanMapMarkers();
}
jQuery.parseJSON() parses json text to an object, but the callback already returns an object
.done(function(data) {
if (data != null) {
equipValue[i] = data;
http://jsfiddle.net/dw74gk7j/
for var i in *object*
is used to iterate over an object properties.
So in equipValue[i] you seems to have equipValue['131-00004131'] which is
equipValue = {
131-00004131: 'your data'
}
Related
I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:
//I parse my JSON into object and name it data
var data = {
...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
// ...
// "title": "hello guys",
// ...
//}
But the vscode's console show the following error when I run the script
TypeError: Cannot set property 'title' of undefined
If you can assign value to undefined object how can you add item in to object.
But if there is any way that can let me assign value to undefined item, I'll be very happy
Here is the full code if you need
var jsonfile = require('jsonfile')
var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;
jsonfile.writeFileSync(file, tmd, {spaces: 4});
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:
var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;
Probably data has no key named 'post'.
Try this:
data.post = data.post || {};
data.post[name] = content;
EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.
I'm trying to read a JSON API and parse the data into an associative array but I can't seem to get it to work. I must be doing something wrong.
Here is my code:
var matchedValues = {};
$.getJSON(url ,function(data) {
$.each(data, function() {
var value = this["value"];
var climb = this["climb"];
matchedValues[value] = climb;
});
});
console.log(matchedValues); //Outputs Object{}
Any ideas? I don't think I am console logging it correctly or maybe I'm doing something wrong?
Thanks
matchedValues is an Object not an array. try something likmatchedValues['your_key'] to get the value.
I assume that the data coming back from the ajax call is a JSON string, which you wish to parse. If that’s the case, then the problem is already solved using JavaScript’s JSON object:
var matchedValues = {};
$.getJSON(url ,function(data) {
matchedValues=JSON.parse(data);
});
console.log(JSON.stringfy(matchedValues)); //Outputs Object{}
As you see in the above example, you have to reverse the process in order to print it out.
See JSON MDN Article
Try this approach from jquery documentation
EDIT:
$.getJSON(url, function(data) {
var matchedValues = {};
$.each(data, function(key, val) {
items[key] = val;
});
If I understood your question, then your data is an Array of objects, and you want to consolidate them in a big object.
If got it right, then use this approach:
var matchedValues = {};
$.getJSON("ajax/test.json", function(data) {
for (var i = 0; i < data.length; i++) {
for (key in data[i]) {
matchedValues[key] = data[i][key];
}
}
console.log(matchedValues); //this should print your object.
});
The data objects must have different keys or they will be overlapsed.
I am using the google news search api and get back data in json format. I am using ajax to get the data and parse through it.
This is my code:
function doAjax(query){
alert(query);
var target = "https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q="+query+"&rsz=large";
$.ajax({
url: target,
cache: false,
dataType:'jsonp',
success: function(data) {
//alert(data.responseData.results);
for(var x = 0; x < 8; x++){
var title = data.responseData.results[x].titleNoFormatting;
//var content = data.responseData.results[x].content;
//var image = data.responseData.results[x].image.url;
$("#home").append(x+"---"+title+'<hr>');
}
},
error: function(jxhr,e){
alert(jxhr.status+" --- "+e.responseText);
}
});
}
When I run the code this way I get 8 titles. but when I uncomment this line var image = data.responseData.results[x].image.url; I get 3 or 4 results only. I investigated the data being retrieved from google I found that some results has no images. How can I check the json result if it has an image. I still want to display the title of the article even if there was no image.
you should check the image exists before get it's url
if(typeof(data.responseData.results[x].image) == "undefined"){
alert('no image');
}else{
var image = data.responseData.results[x].image.url;
}
What does the response look like? Most browsers have developer tools that will let you see the requests and response. Likely, your loop is choking because data.responseData.results[x].image is undefined so data.responseData.result[x].image.url throws a type error (undefined doesn't have a url property).
To guard against this, just check for it like this:
if(data.responseData.result[x].image) {
var image = data.responseData.result[x].image.url;
}
If data.responseData.result[x].image is undefined then it will evaluate as falsey and the body of the if won't be executed (and won't throw an error that breaks you out of the function).
You can check for image like
if (typeof data.responseData.image != 'undefined' && typeof data.responseData.image.url != 'undefined' ) {
// set the image here
}
Typeof can be used to determine if a variable is defined or not.
Example
var var_one = "";
alert(typeof var_one); // alerts "string"
alert(typeof var_two); // alerts "undefined"
alert(typeof var_two == "undefined"); // alerts "true"
So you can specify:
if (typeof var_two != "undefined")
{
alert("variable is undefined!");
}
else
{
alert("variable is defined... use it!");
}
Taking the above into account, you could do:
var image = "";
if (typeof data.responseData.results[x].image.url != "undefined")
{
image = data.responseData.results[x].image.url;
// You can then specify where the image url will go.
}
So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!
This is my array loop:
var display = Array();
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
I try to turn it into a JSON object by:
data = JSON.stringify(display);
It doesn't seem to send the proper JSON format!
If I hand code it like this, it works and sends information:
data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};
When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.
I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?
I am using this ajax method to send data:
$.ajax({
dataType: "json",
data:data,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.
END SOLUTION
var display = {};
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
$.ajax({
dataType: "json",
data: display,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
jsFiddle with example here
js Performance test here, via jsPerf
script.js
$('#loginform').submit(function(e){
$.ajax({
type:"POST",
url:"/accounts/login/ajax/",
data:$('#loginform').serialize(),
success: function(msg){
var msg = msg;
msg = JSON.parse(msg);
$('#messagestatus').html('');
if(msg.username != null){
$('#messagestatus').append(msg.username);
}
if(msg.password != null){
$('#messagestatus').append(msg.password);
}
}
});
e.preventDefault();
});
returned object
{'username':['Required'],'password':['Required']}
When I am using JSON.parse and I am alerting, it's showing the correct error, but when I am appending it to the messagestatus div its not responding, please help .
Your username and password are arrays in your json.Either make it that your json looks like
{'username':'Required','password':'Required'}
or change your script:
if(msg.username.length > 0)
{
$('#messagestatus').text(msg.username[0]);
}
if(msg.password.length > 0)
{
$('#messagestatus').text(msg.password[0]);
}
Might be significant, might not be, but your json object actually consists of sub-arrays:
{'username':['Required'],'password':['Required']}
^----------^ ^----------^
meaning that the decoded data structure in JS would actually be
obj['username'][0] and obj['password'][0]
First of all, parameters do not need to be redeclared in their function.
then, to parse your json using $.parseJSON() :
msg = $.parseJSON(msg);
Your JSON contains arrays, use msg["username"][0] to access the first string and not the full array.
And I would put e.preventDefault(); as first statement before AJAX.
And .html('') => .empty() but it's the same result.