Current Issue:
I am looking to verify that my JavaScript Object is empty, I am trying to use the following JQuery function jQuery.isEmptyObject however, this not returning the expected results.
Example :
var searchRequest = {
marketId: "",
officeId: "",
partnerId: "",
statusId: ""
}
if (jQuery.isEmptyObject(searchRequest)) {
$("#searchButton").prop('disabled', true);
}
Question:
How can I verify that a JavaScript Object is empty using JQuery.
emptyObject means an object without any properties. Not an object with empty properties.
/**
* #param emptyCheck Function that takes a value and returns true if it's empty to allow for flexible
* definition of a value being empty. Defaults to a simple `!` check
*/
function areAllPropsEmpty(obj, emptyCheck) {
emptyCheck = emptyCheck || (val)=> !val;
for (var prop in obj) {
if (emptyCheck(obj[prop])) return false;
}
return true;
}
It may be because you are using jQuery instead of $ (or vice versa?), there could be a conflict going on.
But you could also achieve that with native JavaScript by using:
Object.keys(searchRequest).length //4
searchRequest is not an empty object. It contains key-value pairs. An empty object is {}.
See the docs for $.isEmptyObject.
Related
I am trying to loop through an array to check if email, phone and alternate phone exist in database my issue is I can't find any function or work around in Angularjs that can help me loop through the array where I have set the the listed through variable
$scope.dataCheck = {
email: $scope.TheEmail,
phone: $scope.ThePhone,
AltPhone: $scope.TheAltPhone
}
I have tried to use indexOf like below still not working
if ($scope.dataCheck.indexOf($scope.TheEmail)) {
//I call a function to check if email exist and return
}
Thank You
I should mention I am using ExpressJs and I am new to Javascript
While you are technically correct that objects in JavaScript are associative arrays, they are not Arrays as such. Compare the object property to the value you are searching for.
$scope.dataCheck = {
email: $scope.TheEmail,
phone: $scope.ThePhone,
AltPhone: $scope.TheAltPhone
}
if ($scope.dataCheck.email === $scope.TheEmail) {
//I call a function to check if email exist and return
}
If you simply want to see if the has a value, you can check
if (typeof $scope.dataCheck.email !== "undefined") { ... }
if (myArray.filter(x => !x.TheEmail || !x.ThePhone || !x.TheAltPhone).length == 0) {
// do something
}
if a value is undefined, null or empty ("") javascript will return false. Filter function will return values which contains the expression and count them with length without loop through all items.
about filter you can find here more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=control
Hope this helps.
Can you tell me how to check the JavaScript object has a value ? This vm.occupantDetail.contactDetail object is neither null nor undefined.It looks like as shown below at run time.
It defines as shown below.
vm.occupantDetail = {
contactDetail: {},
};
You can find the it using
Object.keys(vm.occupantDetail.contactDetail).length
It appears from your code that your vm.occupantDetail.contactDetail object is simply an empty object, and the __proto__ property that you are seeing is the protoype property of the Object. If you want to check if an object is null, the following conditional will do the job.
if (obj == null) { ... }
However, it appears that you want to check if an object is empty, which is different. If you want to check if a specified object has no assigned properties, try the following function.
function isEmpty(map) {
for(var key in map) {
if (map.hasOwnProperty(key)) {
return false;
}
}
return true;
}
check it by jQuery.isEmptyObject()
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" });
https://api.jquery.com/jQuery.isEmptyObject/
Check the length of your object also the length of your keys.
if (Object.keys(vm.occupantDetail.contactDetail).length > 0)
{
// vm.occupantDetail.contactDetail has values
}
Here is some JSON:
{
"environments":{
"production":{
"zmq_config":{
"host":"*",
"port":"7676"
},
"redis_server_config":{
"host":"localhost",
"port":"26379"
}
},
"dev_remote":{
"zmq_config":{
"host":"*",
"port":"5555"
},
"redis_server_config":{
"host":"localhost",
"port":"16379"
}
},
"dev_local":{
"zmq_config":{
"host":"*",
"port":"5555"
},
"redis_server_config":{
"host":"localhost",
"port":"6379"
}
}
}
}
I want to create a test in my test suite that ensures all of the properties have the same properties of their complements.
For example, for each property of "environments", I want to check that they have the same properties; in this case they do - they all have 2 properties "zmq_config" and "redis_server_config". Now I want to do at least one more level of checking. For properties "zmq_config" and "redis_server_config", I want to check that they in turn have the same properties "host" and "port".
You get the idea.
Is there a library that can do this? Is there some sort of JavaScript identity operator that check for this, just looking at the top level objects?
Now the easiest way I can think of doing this is simply to iterate through and look at each property with the same name (making the assumption that properties with the same name are in the same place in the object hierarchy), and then simply seeing if they have the same subproperties.
Is Underscore.js the best option? It seems Underscore has this functionality which might work:
_.isEqual(obj1, obj2);
from my research it looks like this is the best candidate:
_.isMatch(obj1,obj2);
For each object to test, you can use Object.keys function to extract the keys of the object and then compare them, because you only want to know if properties are equals, the value not matters.
Then, when you extract the keys of each object, you can compare using _.isEqual function by provided by lodash instead of underscore (usually lodash has better performance).
To automate as possible, you should create a recursive function to extract the keys and compare them.
Hacked this real quick but it should do you justice. It returns true if all nested object keys match. At each level it checks if the array of keys matches the other object's array of keys and it does that recursively.
function keysMatch(data1, data2) {
var result = null;
function check(d1, d2) {
if (result === false) {
return false;
}
if (_.isObject(d1) && _.isObject(d2)) {
if (allArraysAlike([_.keys(d1), _.keys(d2)])) {
result = true;
_.forOwn(d1, function (val, key) {
check(d1[key], d2[key]);
});
} else {
result = false;
}
}
return result;
}
return check(data1, data2);
}
function allArraysAlike(arrays) {
return _.all(arrays, function (array) {
return array.length == arrays[0].length && _.difference(array, arrays[0]).length == 0;
});
}
console.log(keysMatch(json1, json2));
http://jsfiddle.net/baafbjo8/2/
If you want a simple true/false answer, then a simple function can be created from basic javascript.
The function below uses ES5 features, but wouldn't be much more code using plain loops (and run a bit fast to boot, not that it's slow).
/**
* #param {Object} obj - Object to check properties of
* #param {Array} props - Array of properties to check
* #returns {boolean}
**/
function checkProps(obj, props) {
// List of members of obj
var memberNames = Object.keys(obj);
// Use keys of first object as base set
var baseKeys = Object.keys(obj[memberNames[0]]);
// Check every object in obj has base set of properties
// And each sub-object has props properties
return memberNames.every(function (memberName) {
// Get member
var member = obj[memberName];
// Get keys of this member
var memberKeys = Object.keys(member);
// First check that member has same keys as base, then that each sub-member
// has required properties
return memberKeys.length == baseKeys.length &&
baseKeys.every(function(key) {
return member.hasOwnProperty(key) &&
// Check sub-member properties
props.every(function(prop) {
return member[key].hasOwnProperty(prop);
});
});
});
}
console.log(checkProps(env,['host','port']));
For EcmaScript ed 4 compatability, requires polyfills for Array.prototype.every and Object.keys.
I have a class which uses certain properties throughout methods.
function MyClass(elementSelectors) {
this.elements = {};
for (var elementSelector in elementSelectors) {
this.elements[elementSelector] = document.querySelector(elementSelector);
}
}
myClass.prototype.usesAnElement = function () {
console.log(this.elements['header']);
};
var elementSelectors = {
headr: '[class="header"]' // this is sort of an error?
}
var myClass = new MyClass();
Now I'm thinking of future errors. What if someone accidentally misspells a property. I'm wondering if there was a secret way of requiring only certain properties (other than checking them in a separate array containing the possibilities).
You can test the property against a map of available ones and only attempt to use it if it's valid
//available properties
avail = {
"header": true, //or anything that evaluates to true
"foo": true,
"bar": true
}
//test if a property is valid before trying to do something with it
if (Object.prototype.hasOwnProperty.call(avail, elementSelector)) {
this.elements[elementSelector] = document.querySelector(elementSelectors[elementSelector]);
}
Edit
Or, if you don't care for IE8 support, or don't mind adding a polyfill for indexOf you can use arrays (solution suggested below).
First of all, I converted a Plist(XML formatted) to JSON with some online tool, this isn't the problem. I managed to pick the important values from this rather big JSON file. With this important information I am rebuilding a new JSON file that is very lean and contains information I can use for a plug-in — that I will create later.
The plist conversion to JSON is ugly. At some point <true/> and <false/> are converted to JSON, leaving this in the JSON: "false":"", or "true":"",.
I am using jQuery
check JSfiddle for an example jsfiddle example
or here
// Simplified (not really a JSON file, but this will do it for explaining)
var themeJSON = {
"item": {
"false": "",
},
};
// I need to know if its enabled: "true" or disabled: "false"
// function for checking if this is the default option
function checkDefault() {
// true is a keyword!
if (themeJSON.item.true) {
return "1";
// so is false!
} else(themeJSON.item.false) {
return "0";
}
}
Maybe I use some other function such as find() ?
updated for answer:
thanks to the comments, this is what I have now:
function checkDefault() {
if (item.hasOwnProperty("true")) {
return "1";
} else if(item.hasOwnProperty("false")) {
return "0";
}
}
Try using the property name as a string:
if (themeJSON.item['true']) {
return '1';
}
else if (themeJSON.item['false']) {
return "0";
}
edit — a comment correctly points out that though accessing the properties by string value will indeed work, your code is otherwise flawed. If the properties are really being given empty string values, then what you really need is a way to test whether the property is there at all, and not (as this code does) just check the value of the property:
if (typeof themeJSON.item['true'] !== 'undefined') { ... }
or, alternatively:
if ('true' in themeJSON.item) { ... }
An explicit check for equality against the empty string would do too:
if (themeJSON.item['true'] === '') { ... }
When an object property has a name which is a reserved keyword, the array index notation can be used to reference it.
A way of checking whether item has a property named false:
> themeJSON.item.hasOwnProperty("false");
true
This not ideal because a single object could have both a false property and a true property.
In JS, foo.bar is the equivalent of foo['bar']. Therefose:
if (themeJSON.item['true'] === "")
Note the need for === as false == "" but false !== "".
Also, I must nitpick. themeJSON is no longer JSON since it's not a string - it's just another JavaScript object. You shouldn't confuse those two.
Try this code
function checkDefault() {
// true is a keyword!
if ("true" in themeJSON.item) {
return "1";
// so is false!
} else if ("false" in themeJSON.item) {
return "0";
}
}