What is the best way to determine if an item in an array is not empty?

Let's consider an array:

arr = [{}, {}, {}, {}]

If we want to determine the length of the array by counting only objects that contain at least one property, we can do this:

[{}, {name: "Manchester United", odds: 3}, {}, {}] // 1

[{}, {name: "Liverpool", odds: 1}, {name: "Chelsea", odds: 2} ,{}] // 2

Is there a way to achieve this goal?

Answer №1

arr.filter(x => Object.keys(x).length).length

Another way to understand the code above is that the Object.keys() function returns the names of properties from a given object. The first .length filters only items with at least one property, while the second .length counts how many objects meet this criteria.

UPDATE:

In the [].filter() method, it takes a function that results in a true or false value. Any number greater than 0 is considered as true, which is equivalent to .length !== 0.

The assumption made here is that every element in the array is non-null. With this assumption, checking for null values inside the [].filter() doesn't make sense. In TypeScript, this provides a static check for the variable arr. If this assumption is incorrect and there are null values present, an error will be thrown, something that I prefer as it helps uncover issues. Runtime errors are not hidden in my code, and if there are any, I will reassess the underlying assumption. However, I don't think that's the case here.

Answer №2

If you run the following code:

arr.map(x=> Object.keys(x).length)

you will receive:

[ 0, 0, 0, 1 ]

When an object is empty, it has no keys and therefore its length is 0.

To obtain a true/false result, use the following code:

arr.map(x=> Object.keys(x).length).some(x=>x>0)

Examples:

console.log("[{},{}]", [{},{}].map(x=> Object.keys(x).length).some(x=>x>0))

console.log("[{},{a: 1}]", [{},{a: 1}].map(x=> Object.keys(x).length).some(x=>x>0))

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

Parsing JSON data in JavaScript with multiple objects

I just received a JSON Object from an HTTP request [ { "location": { "name": "Seattle, WA", "lat": "47.604", "long": "-122.329", "timezone": "-7", "alert": "", "degreetype": "F", "imagerelativeurl": "http:&b ...

Encountering an issue in next js where attempting to access properties of an undefined variable is resulting in an error with the

"next": "13.0.7" pages version An error occurred in production mode, displaying the following message in the console: TypeError: Cannot read properties of undefined (reading 'push') Additionally, an application error popped ...

Using Backbone to Handle Different Data Formats

I have a unique text file containing date-time data in the format below: 2014-03-14T16:32 2014-03-15T13:04 2014-03-16T06:44 ... I want to use this static file as a read-only data source for my backbone collection. However, the current format is not suita ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...

In WPF/C# programming with Newtonsoft, it is necessary to establish a condition using if/else statements before modifying a .json file based on true/false

As a novice navigating a WPF application, I am faced with the task of updating specific values in an external JSON file. These values are restricted to only "true" and "false" outcomes. { "option1": false, "option2": false, " ...

Express Angular Node Template Render throwing an error: module 'html' not found

I am currently in the process of creating a web application using AngularJS with ui-router for routing via $stateProvider, ensuring that only the specified states are displayed in the ui-view. In my server.js file, I have set up an initial framework such ...

Extracting data from JSON response

The JSON output is as follows: [{"Post":{"name":"Name1","text":"Text1"}}, {"Post":{"name":"Name2","text":"Text2"}}] In attempting to retrieve the values, I used the following code: var data = $.parseJSON(result) // converting JSON to object I tried acc ...

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

Ways to switch the class of the nearest element

When an image within the .process class is clicked, I am using the following code to toggle the class of .process-info to .process--shown. The code successfully toggles the class; however, it affects all elements on the page with the class of .process-inf ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

I designed my higher-order component to allow for dual invocations. How can I integrate Redux within this framework?

I have implemented my higher-order component (HOC) in such a way that it can be invoked twice, emphasizing the concept of "functional programming". However, I am facing challenges in connecting Redux to access state and certain functions. I would greatly ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Using the AJAX post method to generate a JSON object from database results and send it back to a jQuery UI Dialog

I wrote a script that loads sample images from the database based on the relevant category when the page loads. Here's a simplified version of the PHP script: <?php $category = 'granite'; $samples = 'SELECT * FROM material WHERE ma ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

When incorporating sequelize's belongsTo and hasOne methods, you may encounter an issue where the call stack size surpass

Within my Discussion entity, I have: Discussion.hasOne(sequelize.import('./sound'), { relations: false }) While in the Sound entity, the relationship is defined as: Sound.belongsTo(sequelize.import('./discussion')) To load t ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...