JSON check if no data is available - javascript

I am using this code to get data from json.
$.each(data.id, function(index, value){
output += '<li>'+value.title+'</li>';
}
$('#listview').html(output).listview('refresh');
Sometimes there are no records to display.
How can I know if there are no records and display an alert example: alert('No records'); ?

I am assuming that the data.id is an array, since you used$.each on it:
if (data.id.length == 0) {
// no data
}

In general use this code in javascript to check if an array is not empty :
if (myArray.length) { // javascript shortcut for data.id.length>0
alert('no elems found');
}
In your specific case the following code should works :
if (data.id.length) {
$.each(data.id, function(index, value){
output += '<li>'+value.title+'</li>';
});
$('#listview').html(output).listview('refresh');
} else {
alert('no records found ');
}
Hope this helps.

The most general way to check if there is data in object is to use the
length
method.
But you should be very careful. For example if you data is in the following format:
SourceData =[
{
ID:1,
Title:'Test1',
},
{
ID:2,
Title:'Test2',
},
{
ID:3,
Title:'Test3',
},
]
And you do the following check:
if(SourceData.ID.length>0)
and because of some reason(error on server,request timeout,etc) the "SourceData" is not defined, an JavaScript error is going to be thrown.
That's why I am using combination of conditions:
if(typeof SourceData==='undefined'|typeof SourceData.ID==='undefined'|SourceData.ID.length==0)
Then if there is something wrong with the "SoruceData" (it is undefined) a message "No Data" will be shown. Or when the "SourceData" is initialized, but for example someone have changed the structure of the return data from the server (it is no more "ID", it is now "TitleID") no error will be generated.
Note, that I am using "|" instead of "||". This mean, if one of the conditions is "true", the right of him condiations, will not be executed.

Related

Javascript Papaparse Select specific columns using Lodash _.pick() results in empty data

As stated in previous questions here and on Google, I've added a step function to alter the data and provide me with the specific columns I need.
Here was a comment that said to use Lodash _.pick() method: https://stackoverflow.com/a/59944480/4236332
However, when doing that I end up with a completely empty results output.
Code:
parseFile(){
Papa.parse( this.file, {
header: true,
skipEmptyLines: true,
step: (results, parser) => {
results.data = _.pick(results.data , [ 'column1', 'column2']);
return results;
},
complete: function( results ){
console.log(results.data)
this.content = results;
this.parsed = true;
}.bind(this)
});
}
Before vs. After:
First console log holds the colums in the JSON I need plus several I want to filter out, Second log is completely empty.
Tried removing it from the step function and doing it in the complete function but same output.
EDIT 1:
I have tried testing the _.pick function on results.data[0] and this does work, so something is preventing _.pick() of looping through all json records in the list results.data?
Managed to fix this issue by looping through it with a _.map() function. This way it goes through every object in the array with the ._pick() method.
results.data = _.map(results.data, obj => _.pick(obj, [ 'column1','column2']));

How to get only 1st element of JSON data?

I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.

how to build json array dynamically in javascript

I receive a json object with some number of quick reply elements from wit.ai, like this:
"msg": "So glad to have you back. What do you want me to do?
"action_id": "6fd7f2bd-db67-46d2-8742-ec160d9261c1",
"confidence": 0.08098269709064443,
"quickreplies": [
"News?",
"Subscribe?",
"Contribute?",
"Organize?"
],
"type": "msg"
I then need to convert them to a slightly different format as they are passed to FaceBook Messenger as described in the code below. Wit only exposes 'msg' and 'quickreplies.' Can you suggest a good way to do this? It goes after "console.log(element)" as far as I understand.
if (quickreplies){
// got simple array of quickreplies
// need to format quickreplies for FB:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"Red",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
// },
// {
// "content_type":"text",
// "title":"Green",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
// }
console.log('we got quickreplies, here they are:');
var quick_replies = []; // ??
quickreplies.forEach(function(element) {
console.log(element)
});
}
else (console.log('no quickreplies'));
In the above example, the end result should be this:
"recipient":{
"id":"USER_ID"
},
"message":{
"text":"Pick a color:",
"quick_replies":[
{
"content_type":"text",
"title":"Red",
"payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
},
{
"content_type":"text",
"title":"Green",
"payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
}
]
}
I am not sure if this has been a course of confusion, but there is no such thing as a "JSON object". One works with data objects returned by JSON.parse in the same manner as working with any other object. Before sending to FB, of course, data objects have to be converted into JSON string format using JSON.stringify. This might occur automatically in some code libraries depending on how the data is sent.
Here's an example of preparing a quick-replies array - I simply chose an example structure for the payload and went with it. The quick_replies array is still an object and has not been converted to a JSON string.
Edit the format of a text only payload, shown in the first text only example for quick replies indicates the payload is a string. The code below had been updated to meet with this requirement.
// test values for quickreplies:
var quickreplies= [ "News?", "Subscribe?", "Contribute?", "Organize?" ];
/********
convert quickreplies to quick_replies array
using an example payload of:
{ "text" : "text string", // button text
"index" : index, // index into quickreply for button
"other": "tbd" // anything else needed in a reply
}
*********/
var quick_replies;
if (quickreplies) {
console.log('we got quickreplies, here they are:');
quick_replies = quickreplies.map( function(element, index) {
var payload = {
text: element,
index: index,
other: "tbd" // example value only.
};
var payloadString = JSON.stringify( payload);
console.log(element);
var quick_reply = {
content_type: "text",
title: element,
payload: payloadString
};
console.log("** converted to : " + JSON.stringify(quick_reply));
});
quickreplies=null; // housekeeping
}
else {
console.log('no quickreplies');
quick_replies = undefined; // or [] ?
}

Parsing a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"}
{"__v":0,"_id":{"$oid":"55ef49dd5d610eab18719deb"},"admin":true,"email":"emaple2#gmail.com","last_login":"12:25:24 AM","name_surname":"user2","password":"qwerty123"}
{"__v":0,"_id":{"$oid":"55f0173bb3322bf560724fd1"},"admin":true,"email":"emaple3#gmail.com","last_login":"10:25:24 AM","name_surname":"user3","password":"qwerty123"}
Hello, I working in nodeJS file and there I have a collection of JSON objects and I would like to make a search through it. For each user from this list I need to compare the field "last_login" .
I am new to nodeJS can someone help? Thank you!
This is what i have tried:
User.find({}, {last_login: }, function(err, docs) {
if (err) {
return res.json({ success: false, message: 'Failed to display last logins.' });
}
docs.forEach(function(doc, index) {
res.json({success: true, message: 'time of last login', last_login: doc.last_login});
})
//res.json(users);
});
});   
Where last_login is a field in the User object and basically I need to iterate over all users in the db and extract only the last_login and display in in the response.I don’t know what value to put in the find() inside the curly braces
this is the part where I am stuck
I’ve slightly changed the function and it returns a JSON object containing the info about one user that is matched with the search query. The problem is, the console displays the result, as a whole object, although I want to get only a specific key value pair and namely last_login: value
function searchByUserName(name_surname) {
    return list.filter(function(user) {
        return user.name_surname === name_surname;
    });
}
var a = searchByUserName('user1');
for (last_login in a ) {
  if (a.hasOwnProperty(last_login)) {
    console.log("last_login" + "=" + JSON.stringify(a[last_login]))
  }
}
Can you tell me please, what change to make in order to get only the last_login key
here is a sample result from the console.log() that I receive:
last_login={"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"}
although I want last_login = “last_login”: 11:25:24 AM
Assuming it's an array of objects like bellow.
var users = [{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"},
{"__v":0,"_id":{"$oid":"55ef49dd5d610eab18719deb"},"admin":true,"email":"emaple2#gmail.com","last_login":"12:25:24 AM","name_surname":"user2","password":"qwerty123"},
{"__v":0,"_id":{"$oid":"55f0173bb3322bf560724fd1"},"admin":true,"email":"emaple3#gmail.com","last_login":"10:25:24 AM","name_surname":"user3","password":"qwerty123"}];
you can create a function like bellow
function searchByLastLogin(last_login) {
return users.filter(function(user) {
return user.last_login === last_login;
});
}
console.log(searchByLastLogin("12:25:24 AM"));
console.log(searchByLastLogin("10:25:24 AM"));
console.log(searchByLastLogin("11:25:24 AM"));
It will retrun a array of users whose last_login will match to given parameter last_login.
Update
What I understood from your comment bellow, you want last logins of every user.
For that you can do something like bellow
var last_logins = users.map(function(user){
return user.last_login;
});
console.log(last_logins); //prints [ '11:25:24 AM', '12:25:24 AM', '10:25:24 AM' ]
References
filter | map
I don’t know what value to put in the find() inside the curly braces this is the part where I am stuck
If I understand correctly, you only want to get the last_login field for the user model, and that's what you're struggling with ?
According to the documentation, this should work if you only want to get that field :
User.find({}, {last_login:1, _id:0})

Javascript check json output is empty

If I have data in json like this :
{"items":[{"id":"2049","channel_code":"HBD","channel_name":"HBO HD"}]}
And if you search my data to the server could not find results like this :
{"items":[]}
Of output as above, how do I read that my data does not exist or is empty?
I have written some code that I got but have not found the results I want.
This code :
var data = { Name: "John Doe", Age: 25, Address: null, CityState: "Denver, CO" };
for (member in data) {
if (data[member] != null)
//Do something
}
or
if (myObject == '') {
alert('this object is empty');
}
Maybe someone can help me find a way out of this example.
Please help
To check whether your array is empty, just use the respective length property:
if ( data['items'].length < 1 ) {
// it's empty
}
You want to check if data.items.length > 0. Assuming
var data = {"items":[]};
for (member in data) {
if (data[member] != null)
//Do something
}
code inside for will not run because length of data is 0
if (myObject == '') {
alert('this object is empty');
}
myObject wont be null because the object actually is there and its an empty array
you should check for myObject.length because its an empty array

Categories

Resources