How can i validate an object of arrays that's passed as a parameter to my jQuery plugin to make sure it contains specific members/names?
For example, I want to validate if this object below has 'name', 'ID' & 'Location', all three members, which in this case should be true.
var arr = [{
name: 'Johny',
ID: 1,
Location: 'USA'
}, {
name: 'Mike',
ID: 4,
Location: 'CAN'
}];
Thanks in advance.
Johny
You can use Array.prototype.every method to test that every object in array conforms necessary keys rules:
var valid = arr.every(function(obj) {
var keys = Object.keys(obj);
return keys.length === 3 && 'name' in obj && 'ID' in obj && 'Location' in obj;
});
You should really make an effort (and show what you've tried and why it didn't work).
There are many ways to do what you're asking. Here is one:
arr.forEach(function(object) {
if (!object.name || !object.ID || !object.Location) {
throw Error("Missing properties");
}
});
You could check each property individually and throw an error that said what property (or properties) was missing if that's desired.
You can check each property exists by using Object.hasOwnProperty() like so:
function isValid(arr){
// If arr is an array
if( arr && arr.constructor === Array){
// For each item
for(var i=0, l=arr.length; i<l; i++){
var item = arr[i];
if( !typeof item !== 'object'
|| !item.hasOwnProperty('name')
|| !item.hasOwnProperty('ID')
|| !item.hasOwnProperty('Location')
// This is to check if it has *exactly* those 3 properties and no more
|| Object.keys(arr).length != 3){
return false;
}
}
return true;
}
return false;
}
Related
I have list of objects from which I wanted to take out the particular field but I also wanted to remove duplicates also. I have written some code snippet but I wanted to make it more concise. I have one restriction that my project uses ES5. So, please suggest accordingly.
var type = [];
obj.forEach(function(o) {
if(o.type && o.type !== 'null')
type.push(o.type);
});
return type.filter(function filterDuplicates(elem, pos) {
return type.indexOf(elem) === pos;
});
please suggest a better way to doing this. Input obj would be something as follows:-
[
{
'type': 'string'
},
{
'type': 'string'
},
{
'type': 'integer'
}
]
Result should be ['string', 'integer']
You can use type.indexOf to avoid adding duplicates. indexOf looks for a value and returns its index if found, else it returns -1.
var type = [];
obj.forEach(function(o) {
if(o.type && o.type !== 'null' && type.indexOf(o.type) === -1)
type.push(o.type);
});
This is a little shorter (not by much), but only needs to use one method reduce instead of a combination of forEach and filter.
var obj = [{ 'type': 'string' }, { 'type': 'string' }, { 'type': 'integer' }];
var result = obj.reduce(function(p, o) {
if (!o || !o.type || p.indexOf(o.type) !== -1) return p;
p.push(o.type)
return p
}, [])
console.log(result)
I often like to use object properties to remove duplicates, especially for long lists. If you have a short list, using indexOf is fine. However, if you have a long list, this become more efficient. Essentially, "types" below is just used to store the type names as properties. Setting it to true is just to give it a value. Doesn't matter what you assign to it - all you care about is the property names at the end.
var input = [ { 'type': 'string' }, { 'type': 'string' }, { 'type': 'integer' } ];
var types = {};
var result = [];
input.forEach(function (obj) {
if (o.type) {
types[o.type] = true;
}
});
for (var t in types) {
result.push(t);
}
I have an array of objects, where I want to see if the "value" for a "key" in any of the objects is "null". i.e:
var array =
[{name:{} address : "something"},
{name:null address : "something2"},
{name:{} address : "something23"}]
In the above I want to check if any of the name object is null, return false
Can anyone help or direct to the appropriate sources?
Use Array's some().
var data = [
{ name: ..., value: ... },
...
];
var hasUndefinedName = data.some(e => e.name===null || e.name===undefined);
Or, with older ES5 syntax:
...
var hasUndefinedName = data.some(function(e) {
return (e.name===null || e.name===undefined);
});
And of course if the intention is to remove elements with undefined name, use Array's filter():
var data = [
{ name: ..., value: ... },
...
];
var filtered = data.filter(e => e.name!==null && e.name!==undefined);
This is what you need:
var bool = false;
array.forEach(item => {
bool = bool || Object.keys(item).some(key => item[key] == null);
});
If bool equals true then there is at least 1 element in the array that has a property equal to null;
I put == sign instead of === intentionally, since == null checks for both null and undefined.
I wanted to check if the an object has a property of something and its value is equal to a certain value.
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
There you go, an array of objects, now I wanted to search inside the object and return true if the object contains what I wanted.
I tried to do it like this:
Object.prototype.inObject = function(key, value) {
if (this.hasOwnProperty(key) && this[key] === value) {
return true
};
return false;
};
This works, but not in an array. How do I do that?
Use the some Array method to test your function for each value of the array:
function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
console.log(test.some(function(boy) { return hasValue(boy, "age", 12); }));
// => true - there is a twelve-year-old boy in the array
Btw, don't extend Object.prototype.
-- for the property --
if(prop in Obj)
//or
Obj.hasOwnProperty(prop)
-- for the value ---
Using "Object.prototype.hasValue = ..." will be FATAL for js but Object.defineProperty let you define properties with enumerable:false (default)
Object.defineProperty(Object.prototype,"hasValue",{
value : function (obj){
var $=this;
for( prop in $ ){
if( $[prop] === obj ) return prop;
}
return false;
}
});
just for experiment test if a NodeList has an Element
var NL=document.QuerySelectorAll("[atr_name]"),
EL= document.getElementById("an_id");
console.log( NL.hasValue(EL) )
// if false then #an_id has not atr_name
For array, of course you have to browse that array with for
for(var i = 0 ; i < yourArray.length; i++){
if(yourArray[i].hasOwnProperty("name") && yourArray[i].name === "yourValue") {
//process if true
}
}
Typically you'll use something like Object.first:
// search for key "foo" with value "bar"
var found = !!Object.first(test, function (obj) {
return obj.hasOwnProperty("foo") && obj.foo === "bar";
});
Assuming that Object.first will return some falsy value when it doesn't find a match.
Object.first is not a native function but check on of the popular frameworks, they're bound to have one.
Here is another solution for checking if the object has the property but the value of property is not set. Maybe the property value has 0, null or an empty string.
array.forEach(function(e){
if(e.hasOwnProperty(property) && Boolean(e[property])){
//do something
}
else{
//do something else
}
});
Boolean() is the trick here.
What would be the easiest way to determine if a Javascript object has only one specific key-value pair?
For example, I need to make sure that the object stored in the variable text only contains the key-value pair 'id' : 'message'
var keys = Object.keys(text);
var key = keys[0];
if (keys.length !== 1 || key !== "id" || text[key] !== "message")
alert("Wrong object");
If you are talking about all enumerable properties (i.e. those on the object and its [[Prototype]] chain), you can do:
for (var prop in obj) {
if (!(prop == 'id' && obj[prop] == 'message')) {
// do what?
}
}
If you only want to test enumerable properties on the object itself, then:
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && !(prop == 'id' && obj[prop] == 'message')) {
// do what?
}
}
var moreThanOneProp = false;
for (var i in text) {
if (i != 'id' || text[i] != 'message') {
moreThanOneProp = true;
break;
}
}
if (!moreThanOneProp)
alert('text has only one property');
If you know the property you want, wouldn't be quicker to just make a shallow copy of the object, pruned of everything is not needed?
var text = {
id : "message",
badProperty : "ugougo"
}
text = { id : text.id }
Assuming that I've understood correctly your question...
you can stringify it and try to match it with a regEx. Example:
if (JSON.stringify(test).match(/\"id":\"message\"/)) {
console.log("bingo");
}
else console.log("not found");
const hasOnlyKey = (keyName: string, object: Object): boolean => {
const objectKeys = Object.keys(object);
return objectKeys.length === 1 && objectKeys[0] === keyName;
}
I am having a array as follows
var nameIDHashMap = [];
nameIDHashMap.push({
key: name,
value: xmlLength
});
startToEnd.push({
key: $(this).attr("startFrom"),
value: $(this).attr("endTo")
});
I m trying to use the inArray() function like shown below
var variablestart = startToEnd[0].key;
alert("The variable Start is :"+variablestart);
var toEnd;
if(jQuery.inArray(variablestart,nameIDHashMap) > -1) {
alert('found');
}
if ($.inArray(variablestart, nameIDHashMap) != -1)
{
alert("Found");
// toEnd = startToEnd[connectWindow].value
}
else
alert("Fail");
I dont know why always the else loop is called. None of the if loop is getting called. Both of the array has that same key present. Please let me know where I am doing wrong.Thanks!
variablestart is a property of an element in the array, not an element in the array.
var nameIDHashMap = [];
nameIDHashMap.push({
key: 'foo',
value: 'bar'
});
$.inArray(nameIDHashMap[0].key, nameIDHashMap); // this is not an element, -1
$.inArray(nameIDHashMap[0], nameIDHashMap); // this is an element, 0
You are essentially trying to equate the object { key: 'foo', value: 'bar' } to the string 'foo', which are not equal.
http://jsfiddle.net/jbabey/kgYSe/
That's not how .inArray() works. It searches for an array element that's equal to the value you pass in. It doesn't have any provisions for a comparison function.
Even if it did work, what you're assembling there isn't a "hash table". If you want to do efficient lookups by key, you can just create named properties on a simple object:
var map = {};
map.someKey = someValue;
The .inArray() method and anything like it performs a linear-time search through the array, and that's not a very efficient way to do things if you're going to have an "interesting" number of key/value pairs.
edit — if you really must keep a linear unindexed list of named properties, you could use a lookup function like this:
function find( list, key, test ) {
test = test || function(e) { return e ? e.key == key : false; };
for (var i = 0; i < list.length; ++i)
if (test(list[i])) return i;
return -1;
}
To use that, you'd just do:
if (find(nameIDHashMap, someKey) >= 0) {
alert("Found!");
}