Javascript check json output is empty - javascript

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

Related

In this query, what do I need to add so it never displays blanks or null values?

#Query(nativeQuery = true, value = "SELECT " +
"COUNT(DISTINCT pd.id) FILTER (WHERE c.year NOT IN ('2020', '2021', '')) AS \"notCurrent\", " +
This query is for a filter called notCurrent. The problem is, when the filter is selected, it still shows blank values, even though I added '' in the query. What do I need to do so no blanks/null values display when this filter is selected?
UI:
export function forceFilter(key, filterVal, table, dataType, title) {
var newTable = JSON.stringify(table);
newTable = JSON.parse(newTable);
var updated = false;
if (key != "disclosure" && filterVal == "Unknown") {
filterVal = "";
} else if (filterVal == "Not Current") {
filterVal = "notCurrent";
}
}
The default empty "value" may not be an empty string, but null, you may want to try adding this to your WHERE clause
AND c.year IS NOT NULL
you can check length greater than 0 after trimming that column and also check is not null.
Similar as below used sometime back
SELECT
DISTINCT email_id
FROM FCSR_USER_MST
WHERE length(trim(email_id)) >0 and email_id IS NOT NULL
See this linkIt would be helpful for you

Pouchdb join / link documents

I have pouchdb/couchbase data with equipment that has user assigned to them.
Equipment with _id and in the equipment doc there is a checkedOutBy with the user._id as the value. Within the employee object there is user.name. When I get the equipment objects how do I also get the user.name and display with the equipment.
I have searched and read about map/reduce that uses emit and do not grasp the idea. My code that i wrote from what i learned is:
by the way I am also using Angularjs.
field = "eq::"
this.getAllEquip = function(field){
function map(doc) {
if (doc.checkedOutBy !== undefined) {
emit(doc.checkedOutBy, {empName : doc.name});
}
}
var result = database.query(map, {include_docs: true,
attachments: true,
startkey: field,
endkey: field + '\uffff'})
.catch(function (err) {
//error stuff here
});
return result
};
I don't see where the two docs would get together. What am i missing? My result is empty.
The equipment json looks like:
{checkedOutBy: "us::10015", description: "3P Microsoft Surface w/stylus & power cord", equipId: "SUR1501", purchaseDate: "", rCost: 1000, id:"eq::10001"}
Emlpoyee json:
{"firstname":"Joe","gender":"male","lastname":"Blow","status":"active","title":"office","type":"userInfo","_id":"us::10015","_rev":"2-95e9f34784094104ad24bbf2894ae786"}
Thank you for your help.
Something like this should work, if I understood the question correctly:
//Sample Array of Objects with Equipment
var arr1=[{checkedout:"abc1",desc:"item1",id:1},
{checkedout:"abc2",desc:"item2",id:2},
{checkedout:"abc3",desc:"item3",id:3},
{checkedout:"abc1",desc:"item1",id:4},
{checkedout:"abc4",desc:"item3",id:5},
{checkedout:"abc6",desc:"item3",id:6}];
//Sample array of objects with Employee - the "id" in arr2 matches with "checkout" in arr1
var arr2=[{name:"john",id:"abc1"},
{name:"jack",id:"abc2"},
{name:"alice",id:"abc3"},
{name:"james",id:"abc4"}];
var result = []; //final result array
//loop through equipment array arr1
arr1.forEach(function(obj) {
var tempObj = obj;
var checkedout_id=obj.checkedout;
//do array.find which will return the first element in the array which satisfies the given function. This is absed on the assumption that that the id is unique for employee and there wont bwe multiple employees with same id (which is the "checkedout" field in equipment. If the employee is not found, it will return undefined.
var foundname = arr2.find(function(obj) {
if (obj.id == checkedout_id)
return obj.name
})
//Create the object to be inserted into the final array by adding a new key called "name", based on the result of above find function
if (foundname != undefined) {
tempObj.name=foundname.name
}
else {
tempObj.name = "Not found";
}
result.push(tempObj);
})
This is my Pouchdb solution, thank you Vijay for leading me to this solution.
First I get all my equipment. Then I use Vijay's idea to loop through the array and add the name to the object and build new array. I found there is a need to go into the .doc. part of the object as in obj.doc.checkedOutBy and tempObj.doc.name to get the job done.
$pouchDB.getAllDocs('eq::').then(function(udata){
var result = [];
//loop through equipment array
udata.rows.forEach(function(obj) {
var tempObj = obj;
var checkedout_id=obj.doc.checkedOutBy;
if (checkedout_id != undefined) {
$pouchDB.get(checkedout_id).then(function(emp){
return emp.firstname + " " + emp.lastname
}).then(function(name){
tempObj.doc.name = name;
});
}
result.push(tempObj);
})
in my service I have:
this.get = function(documentId) {
return database.get(documentId);
};
and:
this.getAllDocs = function(field){
return database.allDocs({
include_docs: true,
attachments: true,
startkey: field,
endkey: field + '\uffff'});
};

Selecting a JSON object by number not by name

I try to store a JSON object with informations in multiple languages. Im not even sure they way i did it is good, any suggestions are welcome.
My current problem ist, that i dont know how to access the first language without knowing what language it is.
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
document.write(Data[1].Name);
I just want to access the second object, sometimes its "en", sometimes its "de".
Thanks for any tipps!
Here is a pure javascript solution:
First: You get the keys of the object:
var keys = Object.keys(Data);
Then: The keys are stored in a array. You can access them with an index. Like:
Data[keys[0]]
Now: You can use a foor loop or whatever you want :)
Data is an object its not array so you cant access it like Data[0] you can access it like Data.en.
but as you say you dont know any thing about en or de so i suggest that you form the Data object like this :
var Data =[{
lang:"en",
langData:{
Name:"Some name"
}
}]
var Data = {
"NameIntern": "Something intern",
"en": {
"Name": "Some name",
"ModuleOrder": "123,333,22" }
};
var index = 0;
$.each(Data, function(key, val){
index += 1;
if (index == 2){
// key is the language, like in this example key is 'en'
console.log(key);
}
});
var name = (Data.en || Data.de || {})['Name'];
(Data.en || Data.de || {}) get's value of Data.en or Data.de if both doesn't exist, return empty object, so that script doesn't throw exception for Name property
()['Name'] same as myObject['Name'], myObject.Name
assign value to name variable, it will be Some name or undefined at least
If you have more languages, add them all, notice: it will return first found lang
var name = (Data.en || Data.de || Data.ru || Data.fr || {})['Name'];
Use Object.keys method to get list of object property names:
console.log(Data[Object.keys(Data)[1]]['Name']); // "Some name"

how to check null json array

I have a function
function successCallback(responseObj)
{
//alert(JSON.stringify(responseObj));
$.each(responseObj.mname, function (i, mname) {
var array=responseObj.mname[i].rname;
});
here JSON.stringify(responseObj) contains json response like
{"mname":
[{
"mName":"abc",
"url":"abc.com",
"pname":[{
"mName":"abc"
}],
"rname":null
}]
}
here i want to check the value of rname for null value.
i tried using
var array=responseObj.mname[i].rname;
if( !$.isArray(array) || !array.length ) {
alert("currently no referral program available from this brand ");
}
but its for empty value .how can i check for null value..?
use this,problem is you could not assign array value directly.use array.puse() method.
var array = new Array();
array.push(responseObj.mname[0].rname);
alert(array.length);
if (array[0] ===null) {
alert("array is NULL");
}
Live Demo

JSON check if no data is available

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.

Categories

Resources