check object each property value using jquery - javascript

I want to check object's each property value if all value equal to 0 then alert. Below code is performing alert if only one property contains 0
var arr={a:"0", b:"1", c:"2"};
$.each(arr,function(i,val){
if(val=="0")
alert(0)
})

You're actually using an Object, not an Array, so loop with for..in
function allEqualTo(obj, test) {
var key;
for (key in obj)
if (obj[key] !== test)
return false;
return true;
}
Now
var o = {a:"0", b:"1", c:"2"};
if (allEqualTo(o, "0"))
alert(0);
else
alert('foobar');
// foobar alerted

If you want it by jquery use this code:
var bOk = true;
$.each(arr,function(i,val){
if (val != 0) return bOk = false;
})
if (bOk) alert(0);

Related

ESLint error use Object.keys instead of for..in

I'm working on the below code which works perfectly fine. But, ESLint suggest to use Object.keys instead of for..in loop. I tried to iterate the keys, do the search if the match found then return the object. It works with for..in but not with Object.keys. I tried to replace forEach with filter but didn't work for me. Any suggestions.
function searchObj (obj, query) {
// Object.keys(obj).forEach(function(key){
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object') {
return searchObj(value, query);
}
if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
return obj;
}
}
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);
here is the link JS bin
Since you don't really use found object just the fact it is there. You could use Array.prototype.some to avoid looping over every key in obj is you have already found it matches the search query.
function searchObj (obj, query) {
return Object.keys(obj).some(function(key) {
var value = obj[key];
if (typeof value === 'object') {
return searchObj(value, query);
}
return typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);
When you use Object.keys with forEach to iterate through the keys, you are passing a function as callback, so the return statements are for that callback function instead of searchObj.
Instead of returning the result from the forEach callback, you can store it in an external variable (accessed inside the forEach by means of closure), assign it in the forEach, and then return its value. Here I create a variable called foundObj for that:
function searchObj (obj, query) {
var foundObj = null;
Object.keys(obj).forEach(function(key) {
var value = obj[key];
if (typeof value === 'object') {
foundObj = searchObj(value, query);
}
if (typeof value === 'string' && value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
foundObj = obj;
}
});
return foundObj;
}
var demoData=[
{id:1,desc:{original:'trans1'},date:'2017-07-16'},
{id:2,desc:{original:'trans2'},date:'2017-07-12'},
{id:3,desc:{original:'trans3'},date:'2017-07-11'},
{id:4,desc:{original:'trans4'},date:'2017-07-15'}
];
var searchFilter = demoData.filter(function(obj){
return searchObj(obj, 'trans1');
});
console.log(searchFilter);

In Javascript, how can I check the existence of a specific key/value pair nested inside another key/value pair?

For example, this is the value of the object I am processing:
object = {"message":"success","dataList":{"state":"error","count":"25"}}
I know that to check if key "message" exists, I can do the following:
if(object['message']){
//"message" exists. do stuff.
} else{
//"message" does not exist
}
How do I check for the existence of "state" or "count" though?
if(object['dataList']['state']){
// dataList["state"] exists. do stuff.
} else {
// dataList["state"] does not exist
}
or the (in my opinion) more readable:
if(object.dataList.state){ ... }
Edit: It would also be a good idea to check for all parent objects so you will not get an unexpected error when, for example, dataList does not exist on the object:
if (object && object.dataList && object.dataList.state)
try like this:
object = {"message":"success","dataList":{"state":"error","count":"25"}};
if(object.message =='success'){
console.log(object.dataList);// your datalist object here use it
console.log(object.dataList.state);
console.log(object.dataList.count);
} else{
//"message" does not exist
}
if you are trying to check state do this:
if(typeof(object.dataList.state) !='undefined' && object.dataList.state.length > 0){
// dataList.state exists. do stuff.
} else {
// dataList.state does not exist
}
if (object.dataList.state || object.dataList.count) {
// ...
}
First of all, if you are checking the existence of a property, you should use if ('message' in object). If you use if (object['message']), for the case object = {'message': null}, the result is wrong.
In your question, the object is nested into two layers. If there are more than two, you can try a generic solution using recursion:
function findProperty (obj, key) {
if (typeof obj === "object") {
if (key in obj) return true;
var childReturned = false;
for (k in obj) {
childReturned = findProperty(obj[k], key);
if (childReturned) return true;
}
}
return false;
}
var obj = {"message":"success","dataList":{"state":"error","count":"25"}};
findProperty(obj, 'message'); // => true
findProperty(obj, 'dataList'); // => true
findProperty(obj, 'state'); // => true
findProperty(obj, 'count'); // => true

Get value if all objects in chain exist, get fallback value if not

Feel kind of stupid to ask..
I want to get something like this:
var value = $scope.settings.paper.font.color || 0;
The problem is that some of the middle objects may not exist.
Is there an ultimate way to get value if all "object chain" exists and get some fallback if not?
For example, in line above if all objects exists, we may return value of color, but if only $scope.settings exists, and there's no paper object in it, i will get an error, not 0.
First of all: There is no builtin function for it.
Shortest generic solution
Simply wrap it into a try - catch
try {
// handles defaultVal if d is undefined
yourVar = typeof a.b.c.d === 'undefined' ? defaultVal:a.b.c.d;
} catch (e) {
// handles defaultVal if a,b or c are undefined
yourVar = defaultVal;
}
Alternative solution
You could use the following function to safely traverse an object (gv - for getValue):
var gv = function(scope, chainStr, defaultValue) {
var chain = chainStr.split('.');
for (var i = 0; i < chain.length; i++) {
var newScope = scope[chain[i]];
if (typeof newScope !== 'undefined') {
scope = newScope;
} else {
return defaultValue;
}
};
return newScope;
};
Like this:
var a = {b:{c:{d:3}}};
console.log(gv(window, 'a.b.c.d', -1));
// 3
console.log(gv(window, 'a.b.c.e', -1));
// -1
console.log(gv(a, 'b.c.d', -1));
// 3
console.log(gv(a, 'b.c.e', -1));
// -1
Sure, just check for the existence of $scope and each property in its namespace:
var value = (typeof $scope != 'undefined' && $scope.settings && $scope.settings.paper && $scope.settings.paper.font && $scope.settings.paper.font.color) || 0;
The last part of the statement in parenthesis will return the value of .font
Example: http://jsfiddle.net/silkster/gM8uh/
You can also make use of build in $parse service:
var value = $parse('settings.paper.font.color || 0')($scope);
It will make all necessary checks behind the scene.
Demo: http://plnkr.co/edit/1GLb5PEvxMzPMYc5ZxZn?p=preview

Exit from a javascript function

I saw many places similar question but couldn't fix it.
Here's my function:
function validate_form(){
$('#form_data input[type="text"]').each(function(){
value = $(this).val().trim();
if(value != '' && value != null && value != 0 ){
return true;
}
});
return false;
}
Its not exiting on return true;. I have also tried e.preventDefault() but no use.
return will return from the function it is in. In your code, that is the anonymous function you pass to each. See the documentation for each:
You can stop the loop from within the callback function by returning false.
You are returning true, not false so you aren't stopping the loop. Change true to false on line 5 of the function.
function validate_form(){
$texts=$('#form_data input[type="text"]'); //cache the object
var len = $texts.length;
var validItems=0;
$texts.each(function(){
value = $(this).val().trim();
if(value === ''){ // value of a text input cannot be null
// or zero unless you've changed in with JS
return false;
}
validItems++;
});
return len===validItems;
}
The function doesn't exactly show what item is invalid, just returns false if any of the items is invalid.
You have to let the .each() finish before you return from the main function body. You can keep a counter of valid entries you have come across and let the return value depend on that:
function validate_form()
{
var items = $('#form_data input[type="text"]'),
count = items.length,
valid = 0;
items.each(function() {
value = $(this).val().trim();
if (value != '' && value != null && value != 0 ) {
++valid;
}
});
return valid !== count;
}
Btw, I've changed the return value to false if there's at least one invalid entry; assuming you're using this as onsubmit="return validate_form()".

How can I check if a JSON is empty in NodeJS?

I have a function that checks to see whether or not a request has any queries, and does different actions based off that. Currently, I have if(query) do this else something else. However, it seems that when there is no query data, I end up with a {} JSON object. As such, I need to replace if(query) with if(query.isEmpty()) or something of that sort. Can anybody explain how I could go about doing this in NodeJS? Does the V8 JSON object have any functionality of this sort?
You can use either of these functions:
// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
Example usage:
if (isEmptyObject(query)) {
// There are no queries.
} else {
// There is at least one query,
// or at least the query object is not empty.
}
You can use this:
var isEmpty = function(obj) {
return Object.keys(obj).length === 0;
}
or this:
function isEmpty(obj) {
return !Object.keys(obj).length > 0;
}
You can also use this:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
If using underscore or jQuery, you can use their isEmpty or isEmptyObject calls.
Object.keys(myObj).length === 0;
As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).
On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.
If you have compatibility with Object.keys, and node does have compatibility, you should use that for sure.
However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:
JSON.stringify(obj) === '{}'
Consider this solution a 'last resort' use only if must.
See in the comments "there are many ways in which this solution is not ideal".
I had a last resort scenario, and it worked perfectly.
My solution:
let isEmpty = (val) => {
let typeOfVal = typeof val;
switch(typeOfVal){
case 'object':
return (val.length == 0) || !Object.keys(val).length;
break;
case 'string':
let str = val.trim();
return str == '' || str == undefined;
break;
case 'number':
return val == '';
break;
default:
return val == '' || val == undefined;
}
};
console.log(isEmpty([1,2,4,5])); // false
console.log(isEmpty({id: 1, name: "Trung",age: 29})); // false
console.log(isEmpty('TrunvNV')); // false
console.log(isEmpty(8)); // false
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
const isEmpty = (value) => (
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
)
module.exports = isEmpty;

Categories

Resources