how to check null json array - javascript

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

Related

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'});
};

How to get JSON Data depending on other data values in JavaScript

My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

two json file in jquery one for taking data values and other for data types

I am trying to use two json file. One for taking the data type of data and other for getting the data value of data.
Since I don’t know how to use two json file in one so I stored one json values in a variable.
var data = {
“name”: “classxyz”,
“number”:”abc”,
Fields : [
{
“name”: ”studentname”,
“marks”:”int”
“doc”: “failed”
}
]
}
Second json file “student.json”
{
“datasvalue”:
[
{
“studentname”: “Jack”,
“marks”: “18”,
“place”: “newyork”
},
{
“studentname”: “sparrow”,
“marks”: “12”,
“place”: “london”
}
]
}
I want to take the value of data type from the first json and check it into the second json and then show the value of that data type which is taken in first json.
Example: From the first json I search name is “studentname” and now I want to print this “studentname” as a label and search it in the second json file (student.json) and print its value(sparrow) in front of studentname in textfield.
When I print the “marks” it should check from the first json file that it has “int” type and search its value from student.json value that is 18. If I try to put any other value it should not let me enter.
So far, I am able to do the following which is far away from what I have to do.
Can’t we use two json in one program? And why the .inArray is not working this way?
function ViewData()
{
function toArray(obj) {
var result = [];
for (var key2 in obj) {
var value = obj[key2];
result.push(key2);
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
$('#stage').append('<p>'+ key2+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
}
return result;
}
var arra =[];
arra = JSON.strigify(toArray(data));
$('#stage1').html('<p>'+arra + "<br>"+'</p>');
//$('#stage1':contains('day'));
}
$.getJSON('student.json',
function(datas)
{
// Create an array to hold the data.
var items = [];
var storeName=[];
var storeValue=[];
// Parse the data by looking at each entry in the dates object.
$.each(datas.datasvalue,
function(key1, value1)
{
var i=0;
$.each(value1, function(key,value){
storeName[i]= key;
storeValue[i] = value;
$('#stage2').each(function(){
// if($.inArray(key.text(),arra)){
alert($.inArray(key,arra));
$(this).append('<p>'+ key+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
// }
}); // end of stage each funtion
i++;
}); // end of value and key funtion
}); // end of value1 function
}); // end of function (data)

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