Check if value exists in JSON - javascript

I'm doing an ajax call that returns JSON, which includes 3 location zip codes.
These zip codes are:
value2.loc1_zip
value2.loc2_zip
value2.loc3_zip
Then, a "search" form returns a list of zip codes within a search radius. These are:
zipback.zip_codes
and each zipcode is here:
zipback.zip_codes.zip_code
I cannot figure out how to check if value2.loc1_zip, value2.loc2_zip, or value2.loc3_zip are in the list of zipback.zip_codes
I've tried this, but it has not worked:
var grabbed_zips = zipback.zip_codes;
if (grabbed_zips.hasOwnProperty(value2.loc2_zip)) {
...stuff...
}
Here's the raw JSON:
{"counselor_posts":[{"id":"1","firstName":"John","lastName":"Doe","loc1_zip":"30309"},{"id":"3","firstName":"Jeff","lastName":"Kim","loc1_zip":"30315"}]}
{"zip_codes":[{"zip_code":"30324","distance":4.484},{"zip_code":"30376","distance":4.298}]}
Here's the actual jquery I'm using:
$.ajax({
type: "GET",
url: '...url..here...',
dataType: "json",
success: function(zipback) {
var grabbed_zips = zipback.zip_codes;
$.getJSON('/scripts/get_counselor.php', function(data2) {
$.each(data2.counselor_posts, function(name2,value2) {
if (grabbed_zips.hasOwnProperty(value2.loc3_zip)) {
$(".counselor-search-results").append(cat_html2);
}
});
});
}
});

Are you using $.parseJSON to instantiate a JSON Object?
$.parseJSON
This will help yo manage the object. And if the object is a list, then:
var JSONZips = $.parseJSON('{"zips" : {"user1zip":94140, "user2zip": 94107}}');
JSONZips.zips.hasOwnProperty('user1zip');
This would return true.
If you need to find a specific value, then:
function checkForValue(json, value) {
for (key in json) {
if (typeof (json[key]) === "object") {
return checkForValue(json[key], value);
} else if (json[key] === value) {
return true;
}
}
return false;
}
Hope this helps!

I would extract the zip codes contained in the result of the form with a map function, then test if some of the zip codes you have is contained in it.
For example:
var zip1 = "30321", zip2 = "00000", zip3 = "01010"; //zip codes you want to test
var grabbed_zips = {"zip_codes":[{"zip_code":"30324","distance":4.484},{"zip_code":"30376","distan‌​ce":4.298}]}; //search result
//flattened array containing the zip codes in the search result
var zipCodes = grabbed_zips.zip_codes.map(function(zip){ return zip.zip_code; });
//The test you are looking for, either true or false
var someMatch = [zip1, zip2, zip3].some(function(curZip){ return zipCodes.indexOf(curZip) != -1; });
Two arrays are used: one containing the zip codes you have, the other derived from the zip codes in the result of the form.
The some method tests if one of the zip codes in the first array is equal (index!= -1) in the second one.

Related

json array maybe missing a item from time to time how do I set it to 0 and move on. an isnull maybe?

In the weather array I am using, rain only shows up if it's raining. How do I do I skip a field if it is not in the array and move on?
$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/forecast?lat="+latitude+"&lon="+longitude+"&units=imperial&APPID=removed",
success: function(response) {
icon = "wi-day-"+response.list[0].weather[0].main.toLowerCase();
$('#city').html(response.city.name);
$('#country').html(response.city.country);
$('#current_temp').html(Math.round(response.list[0].main.temp)+' ºF');
$('#weather_description').html(response.list[0].weather[0].description);
$('#weather').html(response.list[0].weather[0].main);
$('#max_temp').html(Math.round(response.list[0].main.temp_max)+' F');
$('#min_temp').html(Math.round(response.list[0].main.temp_min)+' F');
$('#humidity').html(response.list[0].main.humidity+' %');
$('#rain_volume').html(response.list[0].rain[3h]+'"');
$('#wind_speed').html(response.list[0].wind.speed+'MPH');
console.log(response);
}
});
The line I am talking about
$('#rain_volume').html(response.list[0].rain[3h]+'"');
This is just an example to avoid all if checks. Personally I would not use it. But just an idea
function always(obj){
return new Proxy(obj, {
get(target, prop) {
if(target.hasOwnProperty(prop) && typeof target[prop] !== 'object'){
return target[prop];
}
return always(target[prop] || {[Symbol.toPrimitive]:() => ''});
}
});
}
let response = {}; // some response
response = always(response);
// this line will not throw any error and will print an empty line
console.log(response.list[0].rain["3h"]+"");
response = {list:[{rain:{"3h":"test"}}]}; // some response
response = always(response);
// this line should print 'test'
console.log(response.list[0].rain["3h"]+"");
If I understand you correctly, you should be able to just skip over it using an IF statement:
if (response.list[0].rain) {
$('#rain_volume').html(response.list[0].rain[3h]+'"');
}
It's not quite correct to say that the rain element isn't in the array. You have an array of objects, and some of those objects may have a rain property and some may not. With that in mind, the answer is here:
check if object property exists - using a variable

Parse not retrieving array of objects

I am storing an array of Javascript objects in Parse under the name 'AcceptedInvitees'. The objects each have two values; an example entry is:
[{"id":"QpAETvSYaB","type":"Requested"},{"id":"Ojjp3TdmTM","type":"unknown"},{"id":"STAUUgVxJp","type":"unknown"},{"id":"AXBC5iZvKQ","type":"unknown"},{"id":"YixKjqrjTM","type":"unknown"},{"id":"b2YwmMcO6n","type":"unknown"},{"id":"DjZePR0Wif","type":"unknown"},{"id":"94Harl1hxm","type":"unknown"},{"id":"1bOE07B0C8","type":"unknown"}]
I am trying to retrieve this value using .get("AcceptedInvitees"), but I am being returned an array of empty objects. For example, retrieving the above entry gives me
[{},{},{},{},{},{},{},{},{}]
This is the specific code I am using to query the data. All the other fields are being retrieved without a problem, but printing node.children gives me the above.
var query = new Parse.Query("UserInvite");
query.include("AcceptedInvitees");
query.get(id, {
success: function (user) {
node.name = user.get("name");
node.TotalInvitees = user.get("TotalInvitees");
node.type = type;
node.children = user.get("AcceptedInvitees");
}
Any help with this would be greatly appreciated!
Parse.Query expects Parse.Object. Therefore, do as following:
var UserInvite = Parse.Object.extend("UserInvite");
var id = 'someUserInviteId';
var query = new Parse.Query(UserInvite);
query.include("AcceptedInvitees");
query.get(id, {
success: function(obj) {
console.log(obj.toJSON());
},
error: function(err) {
console.log(err);
}
});

How to extract data from array in javascript

I have an object (array type) ,its console representation looks like following image . please see the image
This array is created by restangulr using following code ,
restangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = { status: response.status };
feedBackFactory.showFeedBack(item);
}
return response.data;
});
How can I read the elements from this array, I want to extract properties like paginginfo ,also object collection
// The EDIT :1 js libraries I used here angularjsu 1.3.4, and restangular 1.4
My app.js : here I configured rest angular provider
restangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = {
status: response.status
};
feedBackFactory.showFeedBack(item);
}
return response.data;
});
// according to my knowledge this function will intercept every ajax call (api calls) and modify the response , unfortunately I need to apply custom modification because the getlist method must return collection but my api returning object, so according to restangular ,the above code is the possible solution, and here its fine its fetching the data.
userservice.js : this is angular service which using restangular
function(restangular) {
var resourceBase = restangular.all("account");
this.getUsers = function(pagenumber, recordsize) {
var resultArray = resourceBase.getList({
page: pagenumber,
size: recordsize
}).$object;
};
};
according to my knowledge .$object in restangulr resolve the promise and bring back the data, also I am getting the resultArray its looks like in the image in the console, here I can log this array so I think I got all the data from server and filled in this object. I applied some array accessing techniques available jquery and JavaScript like index base accessing , associate accessing but I am getting undefined ie.
resultArray[1] //undifiend;
In angular you can use angular.forEach(items, function(item){ //your code here});
Where items is the array you want to traverse.
If you want to access to one specific position use [], for example var item= items[5].
Then you can do item.property.
UPDATE
Your problem is that you are setting properties in an Array JS Object:
extractedData.paginginfo = data.paginginfo;
You should return the object data like it is and in your controller do something like:
var results= data.result;
var pagInfo= data.paginationInfo;
angular.forEach(results,function(result){});
It looks like the array is numerically indexed (0..1..5); you should be able to simply iterate through it using ForEach (in Angular) or .each (in Jquery).
Something like (JQuery):
$.each(array, function(key, value)
{
// key would be the numerical index; value is the key:value pair of the array index's element.
console.log(value.firstname); // should print the firstname of the first element.
});
First of all, as I said in the comments, you shouldn't be attaching named properties to arrays. Return an object thact contains what you need:
if (operation == "getList") {
return { values: data.result, paging: data.pagingInfo };
}
The getList() method returns a promise, so you need to use that:
this.getUsers = function(pagenumber, recordsize) {
resourceBase.getList({
page: pagenumber,
size: recordsize
}).then(function (data) {
console.log(data.values[0]);
console.log(data.paging.totalRecords);
});
};

How to make 1 variable is equal to multiple values?

Hello I want to add friends on facebook using tokens..
I found this code.
edprens: function(a) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: USER ID/NAME I WANT TO ADD,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
},
example I have.. ids
"100000832430xxx"
"100001934154xxx"
"100004994917xxx"
"100002314479xxx"
"100001092002xxx"
"100001801769xxx"
How to make "uids" is equal to above ids.. so I can add them.?
Thank you
It's too big to post it in comment. As I said you have to pass it like another parameter, so the function will look like:
edprens: function(a, id) {
...
uids: id, // USER ID/NAME YOU WANT TO ADD
...
}
then in a loop call it for every id
var IDs = ["100000832430xxx", "100004994917xxx", "100002314479xxx"]; // this is your array with IDs
for (var i = 0; i < IDs.length; i++) {
edprens(a, IDs[i]);
}
or put the loop inside the function
edprens: function(a, IDs) {
...
for (var i = 0; i < IDs.length; i++) {
$.getJSON("https://graph.facebook.com/me/friends", {
...
uids: IDs[i], // USER ID/NAME YOU WANT TO ADD
...
});
}
...
}
edprens("ids###");edprens("ids###");edprens("ids###"); is not a loop. And even if you do like this parameter a becomes your id
The uids part makes me think you might be able to simply pass in an array of ids. Otherwise use a loop:
Here's it using a loop which should definately work:
//create an array with your ids
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
//loop through that array
$(myIds).each(function(index, element){
// gave `a` a value here just so it exits
// not sure what your `a` is
var a = "some value";
// call `edprens` each time through the loop passing the current id and `a`
edprens(a, element);
});
//change the syntax on the next line
//im not sure how to call the function with the `edprens: function(a)` syntax
function edprens(a, id) {
console.log('function would have been called with id:'+id);
// im commenting out the rest since it requires other code not present
/*if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: id,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}*/
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's it passing an array which might work?...:
//second method (possible but not sure)
//the `uids` part makes me think you might be ale to simply pass in an array of ids like:
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
var a = "some value";
// im commenting out the funnction call
// on the next line since it requires other code not present
//edprens(a, myIds)
//changed
function edprens2(a, id) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: myIds, //here we supply the whole array, might work but Im not familar with the rest of the process so I cant say for sure
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
};

Format returned table data in json

I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.

Categories

Resources