Explore an array of objects in JavaScript to find objects that are not empty

Addressing the heart of my issue:

[
  {amount: 0, name: "", icon: "", description: ""} // default object inserted into array
  {amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]

I am seeking guidance on utilizing lodash find to determine whether an object should be considered "empty" based on the presence of non-zero or non-empty string values in any key.

In this scenario, using lodash find would result in:

[
  {amount: 1, name: "kjfhdkfjh", icon: "67", description: "dasdasd"}
]

Alternatively, it could return undefined.

This is what I currently have:

lodashFind(theArray, function(obj){
   // How do I proceed to iterate through the objects?
});

I am uncertain how to iterate over the objects and implement a logic that returns an object if amount is not 0 and no strings are empty.

Any suggestions?

Answer №1

To accomplish this task, you can utilize the functions _.filter, _.some, _.all, or _.negate from the popular library lodash.

var data = [
    { name:'a', age:0 },
    { name:'b', age:1 },
    { name:'',  age:0 }
];

// Filters out non-empty objects (at least one non-empty field)
console.log(_.filter(data, _.some));
// Result: [{name:'a',age:0},{name:'b',age:1}]

// Filters out fully populated objects (no empty fields)
console.log(_.filter(data, _.all));
// Result: [{name:'b',age:1}]

// Filters out completely empty objects (only empty fields)
console.log(_.filter(data, _.negate(_.some)));
// Result: [{name:'',age:0}]

The functions _.some and _.all specifically look for values that are considered "truthy". Keep in mind that empty strings ('') and zeros (0) are not truthy in JavaScript. Common falsy values include

false, 0, '', null, undefined, NaN
. Everything else is treated as truthy.

Answer №2

With standard JavaScript, accomplishing this task is rather straightforward. All you have to do is filter the array based on the values of the objects contained within it. Here's an example:

var arr = [
  {amount: 0, name: "", icon: "", description: ""},
  {amount: 1, name: "example", icon: "67", description: "description"}
]

arr = arr.filter(function(o) {
  return Object.keys(o).filter(function(key) {
    return o[key] != 0 && o[key].toString().trim().length > 0;
  }).length > 0;
});

FIDDLE

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

`Why is Node.js Express response.download() Not Functioning Properly?`

I have implemented the code below to track active download counts: router.get('/download/:fileName', (req, res) => { let fileName = req.params.fileName; let baseFilePath='/home/filePath'; incrementDownloadCount(fileName) ...

Encountering the issue of "unable to retrieve" when attempting to create an API in Express.js

I am currently developing a REST API using express js, but I encountered an issue with the error message "Cannot GET /api/bears". Here is my code snippet: server.js var express = require('express'); var app = express(); var bodyParser = require ...

Utilizing jQuery callback parameters for interacting with PHP functions via AJAX

I am facing issues with AJAX results when using jQuery. Below are the functions I have defined: <script> function hello(callback, funct, val) { var ret = 0; console.log(val); $.ajax({ type: 'GET', ...

Tips for adjusting a web address provided by a user

I have a JavaScript code that prompts the user to input a URL and then appends it to a div. The code is working fine, but now I am trying to add functionality to edit the entered URL by changing the width and height of any iframes before appending them. ...

What is the best way to verify the font-family using JavaScript?

To verify if the user has installed the font family, we can run a JavaScript function with AngularJS. I am using a Typekit font and have only loaded this service for users who do not have this specific font. ...

Is it better to return JSON before streaming a file through an iframe or sending HTTP headers?

I have created a form that utilizes a hidden iframe to submit a file to a script which then modifies the file and returns the altered version. I have realized that I can avoid saving the file anywhere by simply using echo file_get_contents(tmp);, where tmp ...

Is it advisable to incorporate JSS styles within a personalized React hook?

Struggling to create a reusable SearchBar Component that can hold its own state? Perhaps you've tried making a component for it, only to realize it needs two separate imports to function properly. The code might look something like this: import React, ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

What is the most effective way to combine two getjson responses into a single variable and subsequently manipulate it?

So, I have successfully used getjson for page1, but now I am looking to do the same thing for page2 and then proceed with processing the sitecontent variable. Can someone help me figure out how to make two getjson requests - one for page1 and another for ...

Utilize the map function to modify elements within a nested data structure

I'm attempting to modify objects within nested map functions. I have an array of objects with nested data. When I try to execute it this way, the structure of the data changes and I end up with an array of arrays. All I really need is to add a "level ...

Watching a live video stream in real-time using WebRTC with React

Here is the HTML code <video ref={videos} autoPlay ></video> <Button onClick={() => navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((mediaStream) => { videos.srcObject = mediaStream; videos.onloadedmetad ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

Encountered an error loading the ng-model for a dropdown list in AngularJS

In my JSON object, I have a list of "items" that I want to display in a dropdown menu. However, when using ng-repeat, the dropdown list is appearing blank. To see the code I've used, you can visit this link. HTML: <div ng ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

Utilizing Sails.js: Invoking a YouTube service through a controller

I am facing an issue while trying to integrate Youtube Data API with Node.js in Sails.js. The problem lies with the "fs.readFile" function. Upon launching the service, it returns "undefined". Below is the code snippet for YoutubeService : module.exports ...

Revamp the hues of numerous elements simultaneously using just a single click!

Is there a way to change the colors of various elements (footer, divs, text) background and text color at once using just one button? I attempted to use JavaScript buttons, but I'd prefer not having to name each individual object's button in orde ...

How to align icon and text perfectly in a Bootstrap 5 Button

I am looking to align icons and text within a modal body: <div class="modal-body"> <div class="d-grid gap-2" id="someButtons"> </div> </div> This code snippet demonstrates how I insert buttons ...

Assigning the matrixWorld attribute to an object in three.js

I'm working with a 4x4 transformation matrix in Octave that encodes rotation and position data. After confirming that this matrix represents a valid transformation, I want to use it to set the matrixWorld property of a three.js Object3D object. This i ...

What is the best way to manage a hover effect on devices such as iPads?

As a beginner in web development, I am currently facing a challenge when it comes to managing hover effects on devices like iPads. Initially, my solution was to remove the CSS for hover and replace it with click events, but my client prefers to keep the ho ...