I have the following Javascript array of objects ,I need to check output property if it true for all objects , if output true for all object return true else return false,Can anyone help me to implement that?
var array=[{"id":100,"output":true},{"id":200,"output":true}]
updates
I have try this code but it execute print if just one output is true not all output
function check(){
var data=[{"id":100,"output":false},{"id":200,"output":true}]
data.every(function (e) {
if(e.checked===true){
console.log("print something")
}
});
}
what is the wrong in code?
You can use Array.every() to tests whether all elements in the array pass the test implemented by the provided function
var array = [{"id":100,"output":true},{"id":200,"output":true}]
var istrue = array.every( obj => obj.output === true );
console.log(istrue)
In ES5
array.every( function(obj) { return obj.output === true });
Note that this does strict checking against the boolean true, not just any truthy value
Related
I am looking for a way to search an array to see if a value is present that starts with the search term.
const array1 = ['abc','xyz'];
So a search for 'abcd' would return true on the above.
I have been playing about with includes, but that only seems to check the full value.
Also, startsWith I dont think will work as I believe that checks a string and not values in an array??
You can use the find() function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith() on each value of the array as you intended to do.
Example:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
});
}
console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz
If you want to return true or false instead of the value, you can check if the returned value is different from undefined.
function findStartWith(arg) {
return !!array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
The same snippet with a boolean:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
console.log(findStartWith("hello")); // false
console.log(findStartWith("abcd")); // true
console.log(findStartWith("xyzz")); // true
I'm kinda stuck with an issue. This is the response for my AJAX call.
var test = [
{
"analytics.feature": "false"
},
{
"demo": "true"
},
{
"analytics.demo": "false"
}
]
Now I want to check if analytics.demo is enabled or disabled.
Can I use _.find?
_.find(test, {analytics.demo}); //returns error
I just want to do this
if(analytics.demo) {
//Do something
}
How do I do that? Can someone help?
Instead of iterating objects and comparing, can I use underscorejs/jQuery to get the exact value for a key?
const options = Object.assign(...test)
console.log(options) // { "analytics.feature": "false", demo: "true", "analytics.demo": "false" }
if (options['analytics.demo'] === 'true') {
// ...
}
(Note that this uses ES6. For ES5 use var options = Object.assign.apply(object, test) instead, and you also need to polyfill Object.assign.)
This uses Object.assign() with the spread operator to merge the objects into one, then get the "analytics.demo" option from the new single object. It has to be accessed using bracket notation because the key has a dot in. It is compared to the string true because "false" (string) is true but false (boolean) is false.
There is more information on SO about flattening arrays and converting strings to booleans.
PS is there any way you can get the Ajax call to use proper booleans instead of strings? It would be easier to work with.
You can check if any of the items in the array matches a certain condition like so:
var isDemoEnabled = test.some(function (item) {
return item['analytics.demo'] === 'true';
});
if (isDemoEnabled) {
// Do something
}
If the values were boolean, you could remove === 'true'
Assuming you're using underscore, check out the documentation regarding find:
http://underscorejs.org/#find
Find runs a predicate function for every element in an array and returns a new array that contains every value where the predicate function returned true.
In this case we want to find if the element has a field analytics.demo
To do this we can use the underscore function _.has:
http://underscorejs.org/#has
all in all:
var result = _.find(test, function(elem) {
return _.has(elem, "analytics.demo");
}
);
You could iterate over and check if the key is given and return then the result.
function getKeyValue(array, key) {
var value;
array.some(function (a) {
if (key in a) {
value = a[key];
return true;
}
});
return value;
}
var test = [{ "analytics.feature": "false" }, { "demo": "true" }, { "analytics.demo": "false" }]
console.log(getKeyValue(test, 'analytics.demo')); // 'false' a string with this value
i have a method that returns an object that contains 4 objects:
function getFiles() {
var documents = {};
documents.files1ToBeCompleted = DocumentsService.getFiles1Uncompleted();
documents.files2ToBeCompleted = DocumentsService.getFiles2Uncompleted();
documents.files3ToBeCompleted = DocumentsService.getFiles3Uncompleted();
documents.files4ToBeCompleted = DocumentsService.getFiles4Uncompleted();
return documents;
}
I'm trying to use Underscore function ._isEmpty to verify if the object is empty, i mean the case in which i get an object with empty sub-objects.
But even all its 4 objects are empty, it is not empty because it contains 4 items.
Do you know any way to check if an object is "deep empty"?
Here's what worked for me. It is recursive and takes care of all nested objects (uses lodash).
function isEmptyDeep(obj) {
if(isObject(obj)) {
if(Object.keys(obj).length === 0) return true
return every(map(obj, v => isEmptyDeep(v)))
} else if(isString(obj)) {
return !obj.length
}
return false
}
It first checks if there are no keys, and returns true in that case.
Then it checks the keys and runs isEmptyDeep on each. If the value is an object (or array), it will continue recursion.
If there's an empty array or empty string, length will be 0 and will be considered empty.
If the value is 0, false, or other falsy values, then it would be considered not empty. If you want to consider falsey values as empty, this as the first line in the function above:
if(!obj) return true
Thanks to Bergi that lead me to this working solution:
_.every(documentsObject, function(property) { return _.isEmpty(property); });
that returns true if the object is "deep empty", false otherwise.
In JavaScript, I need to know if all object items are set to true.
If I have the following object:
var myObj = {title:true, name:true, email:false};
I could write something like this :
if(myObj.title && myObj.name && myObj.email){
/*Some code */
};
But I am looking for the simplest way to write it. eg :
if(myObj all is true){
/*Some code */
};
I might have another object with 10-20 items inside it, and will need to know if all are true.
With ES2017 Object.values() life's even simpler.
Object.values(yourTestObject).every(item => item)
Even shorter version with Boolean() function [thanks to xab]
Object.values(yourTestObject).every(Boolean)
Or with stricter true checks
Object.values(yourTestObject)
.every(item => item === true)
In modern browsers:
var allTrue = Object.keys(myObj).every(function(k){ return myObj[k] });
If you really want to check for true rather than just a truthy value:
var allTrue = Object.keys(myObj).every(function(k){ return myObj[k] === true });
How about something like:
function allTrue(obj)
{
for(var o in obj)
if(!obj[o]) return false;
return true;
}
var myObj1 = {title:true, name:true, email:false};
var myObj2 = {title:true, name:true, email:true};
document.write('<br />myObj1 all true: ' + allTrue(myObj1));
document.write('<br />myObj2 all true: ' + allTrue(myObj2));
A few disclaimers: This will return true if all values are true-ish, not necessarily exactly equal to the Boolean value of True. Also, it will scan all properties of the passed in object, including its prototype. This may or may not be what you need, however it should work fine on a simple object literal like the one you provided.
Quickest way is a loop
for(var index in myObj){
if(!myObj[index]){ //check if it is truly false
var fail = true
}
}
if(fail){
//test failed
}
This will loop all values in the array then check if the value is false and if it is then it will set the fail variable, witch will tell you that the test failed.
You can use every from lodash
const obj1 = { a: 1, b: 2, c: true };
const obj2 = { a: true, b: true, c: true };
_.every(obj1, true); // false
_.every(obj2, true); // true
Probably a duplicate of this question.
Silly javascript question: I want to check if an object is the emtpy object.
I call empty object the object that results from using the empty object literal, as in:
var o = {};
As expected, neither == nor === work, as the two following statements
alert({}=={});
alert({}==={});
give false.
Examples of expressions that do not evaluate to the empty object:
0
""
{a:"b"}
[]
new function(){}
So what is the shortest way to evaluate for the empty object?
You can also use Object.keys() to test if an object is "empty":
if (Object.keys(obj).length === 0) {
// "empty" object
} else {
// not empty
}
function isEmpty(o){
for(var i in o){
if(o.hasOwnProperty(i)){
return false;
}
}
return true;
}
You can use this syntax
if (a.toSource() === "({})")
but this doesn't work in IE. As an alternative to the "toSource()" method encode to JSON of the ajax libraries can be used:
For example,
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
jquery + jquery.json
There is not really a short way to determine if an object is empty has Javascript creates an object and internally adds constructor and prototype properties of Object automatically.
You can create your own isEmpty() method like this:
var obj={}
Object.prototype.isEmpty = function() {
for (var prop in this) {
if (this.hasOwnProperty(prop)) return false;
}
return true;
};
alert(obj.isEmpty());
So, if any object has any property, then the object is not empty else return true.
javascript:
cs = 'MTobj={ }; JSON.stringify(MTobj)=="{}"';
alert(cs+' is '+eval(cs));
cs = 'MTnot={a:2}; JSON.stringify(MTnot)=="{}"';
alert(cs+' is '+eval(cs));
says
MTobj={ }; JSON.stringify(MTobj)=="{}" is true
MTnot={a:2}; JSON.stringify(MTnot)=="{}" is false
Caveat! Beware! there can be false positives!
javascript:
cs = 'MTobj={ f:function(){} }; JSON.stringify(MTobj)=="{}"';
alert(cs+' is '+eval(cs));
alert("The answer is wrong!!\n\n"+
(cs="JSON.stringify({ f:function(){} })")+
"\n\n returns\n\n"+eval(cs));