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

Tips for crafting an XPath query to target text contained within the <script> element with the help of PhantomJS

I need to extract specific content that is located within the <script> section of a webpage (at the bottom of the page before the closing </body> tag. I know that regular XPath cannot accomplish this task, so I intend to utilize PhantomJs cloud ...

Efficiently Organizing Data Using Coldfusion Loops in Columns and Rows

My issue lies in pulling data from a database to display on my website. I have three keys/attributes (columns) - PostedDate, DataImage, and Source that need to be shown together in one div with the posted date at the top, image in the middle, and source at ...

Calculate the total of each row in an array with multiple dimensions

I am trying to calculate the sum of each row in a multidimensional array: $number = array ( array(0.3,0.67, 0.3), array(0.3,0.5,1), array(0.67,0.67,0.3), array(1,0.3,0.5) ); The desired result should be as follows: row1 = 1.27 row2 = 1.8 ...

After the update to the page, the DOM retains the previous element

I'm currently developing a Chrome Extension (no prior knowledge needed for this inquiry...) and I have encountered an issue. Whenever I navigate to a page with a specific domain, a script is executed. This script simply retrieves the value of the attr ...

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

Best locations for placing files when integrating Javascript into Wordpress

I have been struggling to make JavaScript work and determine the correct location to place the files. After attempting various methods, I am now wondering what the most logical approach would be. Despite spending a week on this task, the lack of a tutoria ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

The Bootstrap tooltip fails to function properly following a page update or refresh

My tooltip component seems to be malfunctioning, and I suspect the issue lies within the option attributes. I am unsure where the problem is occurring and how to resolve it. The tooltip component was initialized using the code below: var options = { anim ...

What is the best way to add content in JavaScript?

Just diving into the world of JavaScript, HTML, and web development tools here. var labels = {{ labels|tojson|safe }}; After using console.log to check the content of labels with console.log(JSON.stringify(labels));, I got this output: [ {"id":"1", ...

Tips on creating an onclick function in javaScript and linking it to innerHTML

let a = 10; let b = 15; document.getElementById("text").innerHTML = '<div onclick=\'testing("'a + '","' + b + '") > text </div>'; Welcome, I am new to this ...

"Implementing a full page refresh when interacting with a map using

Here is an example of how I display a map on the entire page: <div id="map_canvas"> </div> UPDATE 2: I have successfully displayed a menu on the map, but there is a problem. When I click on the button, the menu appears briefly and then disapp ...

Interact with Circles Through Mouse Movements with d3.js Animation

I am currently utilizing the d3.js library and facing a challenge in meeting the client's requirements. The client has requested for "circles to turn black" and "follow" the mouse when hovered over. I am unsure if d3.js library supports such a featu ...

Can Sequelize be used to perform queries based on associations?

I have designed a data structure that includes an n:m relationship between "Rooms" and "Users." My current goal is to remove or delete a room. To accomplish this, I need to verify if the user initiating the deletion process is actually present in the room ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...

How can React Components be imported into a website that is not built with React?

After developing a site with Node and Express, I am looking to incorporate a page built with React and JSX. As part of this process, I have installed Babel as an npm package and included React in the index.html file like so: <script src="https://un ...

No activity was detected on the UmbracoApiController controller

I am attempting to retrieve data from an Umbraco Api class and send it to a javascript function. Any assistance in resolving the following errors would be greatly appreciated. {,...} Message : "No HTTP resource was found that matches the request URI &apos ...

Updating a Parent component from a Child component in React (Functional Components)

My functional component RoomManagement initiates the fetchRooms function on the first render, setting state variables with data from a database. I then pass setLoading and fetchRooms to a child component called RoomManagementModal. The issue arises when t ...

Having issues with the basic KnockoutJS binding not functioning as expected

There appears to be an issue with my KnockoutJS script that I'm struggling to pinpoint. Below is the snippet of HTML code: <h2>SendMessage</h2> <div class="form-group" id="messageSender"> <label>Select User Type</l ...

Parsing JSON data into different data types in C#

I am looking for a way to transfer various types of data from JavaScript to C#. Specifically, I want to send a JSON object from the JavaScript side using an AJAX call. Here is an example: AnObject = new Object; AnObject.value = anyValue; $.ajax({ typ ...