If every object within the array contains a value in the specified property, then return true

In my current project, I am working with an array of objects that looks something like this:

$scope.objectArray = [
  {Title: 'object1', Description: 'lorem', Value: 57},
  {Title: 'object2', Description: 'ipsum', Value: 32},
  {Title: 'object3', Description: 'dolor', Value: 135}
]

My goal is to check and return true if all the objects in this array have a value stored within the 'value' property.

While considering different approaches, I am currently using a forEach loop. However, I wonder if there might be a more efficient way to achieve the same result.

var isTrue = true;
angular.forEach(objectArray, function(o){
  if (!o.Value){
    isTrue = false; // change variable 'isTrue' to false if no value
  }
});

Answer №1

Utilizing Array#every in conjunction with Arrow function

var isTrue = objectArray.every(obj => obj.Value);

var objectArray = [
  {Title: 'object1', Description: 'lorem', Value: 57},
  {Title: 'object2', Description: 'ipsum', Value: 32},
  {Title: 'object3', Description: 'dolor', Value: 135}
];

var isTrue = objectArray.every(obj => obj.Value);
document.body.innerHTML = isTrue;


Revision:

In order to account for a value of 0, you can implement Object#hasOwnProperty.

objectArray.every(obj => obj.hasOwnProperty('Value'))

var objectArray = [
  {Title: 'object1', Description: 'lorem', Value: 57},
  {Title: 'object2', Description: 'ipsum', Value: 32},
  {Title: 'object3', Description: 'dolor', Value: 0}
];

var isTrue = objectArray.every(obj => obj.hasOwnProperty('Value'));
document.body.innerHTML = isTrue;

Answer №2

One way to achieve this is by using the Array#every() method, excluding 0.

var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 57 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] },
    isTrue = $scope.objectArray.every(function (a) {
        return a.Value;
    });

document.write(isTrue);

Here's a solution that includes a test for 0 as a value.

var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 0 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] },
    isTrue = $scope.objectArray.every(function (a) {
        return a.Value || a.Value === 0;
    });

document.write(isTrue);

Answer №3

If you want to check if every element in an array meets a certain condition, you can utilize the every() method:

var allValuesTrue = myArray.every(function(item) {
    return item.condition;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

Discover the worth within the outcome obtained from the AJAX request

I have an action that returns a tuple containing a boolean value and a string. How can I retrieve the first boolean value from the result, which could be either true or false? This is the action: public Tuple<bool, string> Check This is the AJAX c ...

transforming a cylindrical shape into a curved pipe

Utilizing the capabilities of three.js, I have successfully engineered a captivating scene featuring a textured and meshed cylinder along with a grid boasting lines and vertices. By manipulating the mouse to the left or right, the cylinder elegantly spins ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Data cannot be cleared in the service

I have set up a customer shopping cart on the client side of my application, with a controller managing the functions of the cart and a service injected into that controller. Upon loading the page, I retrieve the contents of the cart from localStorage and ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

I'm struggling to grasp the concept of State in React.js

Even though I'm trying my best, I am encountering an issue with obtaining JSON from an API. The following error is being thrown: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitia ...

Obtain the range of values for a match from an array using Vue.js

I have an array in my Vue.js code with values 25, 100, 250, and 500. I am looking to find the key value that matches a specific range. For example, if the input is 5, then the output should be 25. However, the code I tried returns all values within the ran ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

Creating a jquery DataTable from HTML generated by angular $sce can be done by following these steps

I have created an Angular controller that takes data and generates an HTML table from it. The generated table is being displayed on the page. Now, I want to apply jQuery data tables using that scope variable. The variable contains the HTML code of the tabl ...

What is the best way to import a JavaScript class into the main.js file of a Vue.js project and make it accessible in all components without needing to import it individually in each component

I have developed JS classes that I want to import into the app.js or main.js file of my vue.js project, so that I can create instances of them in various components. Currently, I find myself having to import the same JS class separately in all components w ...

The v-on:click event handler is not functioning as expected in Vue.js

I am currently learning vue.js and facing some challenges. Below is the code snippet from my HTML page: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net ...

What is the best way to reset the ng-init value when a button is clicked?

Can someone help me with this issue? I need to reset the items.total model in my code, but so far it's not working as expected. <div ng-init="items.total"> <ul ng-repeat="x in Arr"> <li ng-init = "items.total.carat = items.tot ...

The code is throwing an error because it is unable to find the property 'vibrate' of an

I am currently trying to implement the ng-cordova vibrate plugin in my ionic application, but I am facing an issue. The console log is showing an error message: Cannot read property 'vibrate' of undefined. Can someone please provide guidance on h ...

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...

Implementing a Class on Page Refresh in Next JS

I am fairly new to using react and nextjs. How can I insert a script in a component to add a class when the page reloads? The code below doesn't seem to work because the page is not yet rendered when I try to add the class for the body tag. const Mode ...