JQuery: Get length of JSON reply? - javascript

In a JQuery getJSON call, how can I tell the length of the JSON that's returned?
function refreshRoomList() {
$.getJSON('API/list_rooms',
function (rooms) {
if (rooms.length > 0) {
$("#existing-room-list").empty();
$("#join-existing-room").text("Join existing room:"); // this shouldn't be here
$.each(rooms, function (index, roomName) {
var newChild = sprintf('<li>%s</li>', index, roomName);
$("#existing-room-list").append(newChild);
});
}
else {
$("#join-existing-room").text("No rooms found.");
}
});
}
For some reason this doesn't work, but if I replace rooms.length > 0 with true, the full list of rooms is printed out.
If rooms is empty, it is returned as {}.

If rooms is empty, it is returned as {}.
Thus, it's not an array, but an object. Objects doesn't have a length. There's only one of it. If you want to denote nothing, then rather use null instead of {}. This way you can use if (rooms) instead.
To learn more about JSON, you may find this article useful.

Try this approach instead, in your situation it should be null when empty:
if (rooms) {

Related

Javascript Equalize Element From Array

Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?
As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));
You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.
I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));
You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find

How to get the JavaScript Object from the given string?

How to get the Object from a string?
I written a localStorage util, in it there are get and set methods.
in the set method:
function fnGet(name){
var getVal=storage.getItem(name);
if(getVal==null){
return console.log('the localstorage did\'t have'+name);
}
if((getVal.split(':-:')).lenght>1){
return eval('('+getVal.split(':-:')[0]+')');
}
return getVal.split(':-:')[0];
}
You can ignore the :-:, it is the separator of the saved data and timestamp.
there is a problem, if the data is stored a JavaScript Object, such like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}:-:1521381469910'
when I use the get method, it will become like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}'
How can I get to the JavaScript Object?
How to optimize my get method?
JSON.parse on your response from the store. localStorage stores everything as strings so you would need to stringify the object at first, as Im supposed you do as otherwise you wouldnt have been able to save it to the store.
Then to retrieve it you would need to parse it to get the javascript object again.
Two things:
Use JSON.parse() instead of eval; it's not only safer, but more descriptive as to what your intent is. Note: this requires using JSON.stringify() on the data being saved in localStorage
Correct your spelling errors; you would never get to the eval/parser block because your length was spelled "lenght"
function fnGet(name) {
let getVal = storage.getItem(name)
if (getVal == null) {
return console.log(`the localstorage did't have: ${name}`);
}
let val = getVal.split(':-:'); // for performance cache the split
if (val.length > 1) { // Spelling error: "lenght" -> length
return JSON.parse(val[0]);
}
return val[0];
}
LocalStorage saves the data stringified. So you should use JSON.parse(yourVariable) to get the data back as JSON
function fnGet(name) {
var getVal = storage.getItem(name);
if (getVal == null) {
return console.log('the localstorage did\'t have' + name);
}
if ((getVal.split(':-:')).lenght > 1) {
return eval('(' + JSON.parse(getVal.split(':-:')[0]) + ')');
}
return getVal.split(':-:')[0];
}
all you needed was JSON.parse which takes a string as an argument and if its a valid object string ,returns an object else throws an error

Angular JavaScript filter function, updating with $scope input

I'm currently writing a little function to take a $scope value from an input field, then add it to a new array containing invited users.
To prevent duplicate entries into the array I'm trying to use JavaScript's filter method.
My problem is when I look at whats being output to the console, the console.log inside the filter function always prints the same Email value, it doesn't seem to update and consider the new input. e.g. a user has added 2 users, the first will be added and the invitesArr will only contain the first Email.
var invitesArr = $scope.invites;
console.log(invitesArr)
console.log($scope.searchContacts)
if ($scope.invites.length >= 0) {
invitesArr.filter(function(invitesArr) {
console.log(invitesArr.Email)
return invitesArr.Email === $scope.searchContacts;
});
if (invitesArr == false) {
courseAccountService.inviteGuestToCourse($scope.courseId,$scope.searchContacts).
then(function(invitation) {
$scope.invites.push(invitation);
});
}
}
Try the below code:
var invitesArr = $scope.invites;
console.log(invitesArr)
console.log($scope.searchContacts)
if ($scope.invites.length >= 0) {
//use arrow operator instead of function.
var duplicateEmails = invitesArr.filter((item) => {
console.log(invitesArr.Email)
//assuming datatype of item.Email and $scope.searchContacts are same else use == for comparision
return item.Email === $scope.searchContacts;
});
//Check for length and then push to your invites
if (duplicateEmails.length==0) {
courseAccountService.inviteGuestToCourse($scope.courseId,$scope.searchContacts).
then(function(invitation) {
$scope.invites.push(invitation);
});
}
}
Hope it helps!!

Use Lodash to find the indexOf a JSON array inside of an [] array

I have an array that looks something like this.
Users : {
0 : { BidderBadge: "somestuff", Bidders: 6, }
1 : { BidderBadge: "somemorestuff", Bidders: 7,}
}
I want to search the array using lodash to find a value inside of each of the user objects.
Specifically, I want to use values from another similar array of objects to find the value.
var bidArray = [];
_.each(this.vue.AllUsers, function(user) {
_.each(this.vue.Bids, function(bid) {
if(user.BidderBadge == bid.Badge) {
bidArray.push(user);
}
});
});
This is what I have and it works, but I want to do it using only one loop instead of two. I want to use something like _.indexOf. Is that possible?
If you want to avoid nesting, you just have to modify Azamantes' solution a bit
var bidders = this.vue.Bids.reduce(function(acc, bid) {
return acc[bid.BidderBadge] = true;
}, {});
var bidArray = this.vue.AllBidders.filter(function(bidder) {
return !!bidders[bidder.Badge];
});
It is difficult to give an accurate answer with an example that doesn't coincide with the input that your provide.
Anyway, supposing your data structures were more or less like this ones, you could solve the problem with lodash _.intersectionWith.
Intersect both arrays using a comparator that checks the correct object properties. Also, take into account that users must go first in the intersection due to the fact that you're interested in its values.
function comparator(user, bid) {
return user.BidderBadge === bid.Badge;
}
console.log(_.intersectionWith(users, bids, comparator));
Here's the fiddle.

Get path of element in object without looping through all elements (second hierachy level unkown)

I have the following object:
var oBadge = {
COMMENT_CREATED: {
FIRST_COMMENT_CREATED: {
code: "FIRST_COMMENT_CREATED",
src: "",
name: "Socializer",
text: "Create a comment for an idea",
condition: {
today: null,
over_all: 1
}
}
}
};
i need to check if a string i get (for example "FIRST_COMMENT_CREATED") is contained in the oBadge model. The object contains more elements - not only the comment_created element. Therefore i cannot define to check it there.
I found the following function to determine wether the element is contained within the object or not, but I also need the contained data, not only the statement whether it is contained or not.
oBadge.hasOwnProperty("FIRST_COMMENT_CREATED")
What i'm basically looking for is a way to skip the second hierachy level on my check - like:
if(oBadge.[<all>]["FIRST_COMMENT_CREATED"] !== undefined) {
// return data
}
There is no way to skip the hierarchy without looping through the object, you should use the for...in loop:
for (var prop in oBadge) {
if(oBadge[prop].hasOwnProperty("FIRST_COMMENT_CREATED")) {
// return data
}
}
Use a function and a loop (for-in):
function find(key, obj){
if(!obj.hasOwnProperty) return false; // no primitive data please!
if(obj.hasOwnProperty(key))
return obj[key];
else return false;
}
for(var key in oBadge){
if(find("FIRST_COMMENT_CREATED", key))
// code
}

Categories

Resources