Remove objects from array that have any falsy key

Is there a way to filter this array to only include objects with truthy values for keys? For example, here is an array:

[
    { foo: NaN, test: 'String' },
    { foo: 2, test: '' },
    { foo: 3, test: 'Something' },
]

I want to create a new array that excludes objects with falsy values for keys. So, in this case, the new array should only contain the third object:

[
    { foo: 3, test: 'Something' },
]

Answer №1

Simply go through each object and filter out those without empty values.

var array = [{ foo: NaN, test: 'String' }, { foo: 2, test: '' }, { foo: 3, test: 'Something' }],
    result = array.filter(o => Object.values(o).every(Boolean));

console.log(result);

Answer №2

Utilize the filter and reduce methods to achieve the desired outcome

const items = [
    { bar: Infinity, trial: 'Text' },
    { bar: 5, trial: 'Another' },
    { bar: 6, trial: 'Nothing' },
]


items.filter(item => Object.values(item).reduce((accumulator, value) => accumulator && value), true)

Answer №3

Iterate through your array and include a condition as shown below:

var array = [
        { bar: NaN, sample: 'Text' },
        { bar: 5, sample: 'Testing' },
        { bar: 7, sample: 'Example' },
    ]; // sample data
var updatedArray=[];
for(var x=0;x<array.length;x++){
    if(array[x].bar && array[x].sample){
       updatedArray.push( array[x]);
    }
}

Answer №4

Bar = 2 is not falsy in this instance, therefore it is also present in the final result.

const data = [
        { bar: NaN, test: 'String' },
        { bar: 2, test: '' },
        { bar: 3, test: 'Something' },
    ];
    
console.log(data.filter(obj => obj.bar));

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

Utilizing Vuejs to initiate a GET request using a method

Currently, I am working on enhancing the functionality of a GET request in Vue. My goal is to attach the request sending action to the form's submit button and also include a parameter from a text field within the form. HTML <html> <head> ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...

The splice function in Angular is mistakenly removing a different record instead of the intended one that was

An issue with the Angular splice function is causing it to delete the wrong record. Here is the code snippet in question. Within the code below, when attempting to delete the record labeled "Pat," the code ends up deleting the record labeled "Max." Please ...

Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically. Unfortunately, I have run into an issue where the delete function does not work when the button is pressed. Her ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

Converting an array of objects into a single object: A step-by-step

I'm looking to transform an array of objects into a final output of objects. My initial array of objects looks like this: [ { "id": "11", "value" : "9999","sample":"1"}, { "id": "22", "value" : "8888","sample":"2"}, { "id": "33", "value" : ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

Encountered an error: "switch/mergeAll/flatten is not a valid function" when working with the http driver

As I delve into learning CycleJS, one thing that has caught my attention is the usage of Cycle's HTTP Driver. It seems that in order to reach the stream level, merging the response stream stream with RxJS switch/mergeAll is essential. However, when at ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

Bring to the front the div altered by a CSS3 animation

Recently, I encountered an issue with a div card that triggers an animation when clicked. The animation involves the card scaling up larger, but the problem arises as its edges get hidden under other cards. To visualize this, take a look at the screenshot ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...

Implementing Vue plugins in your Store: A step-by-step guide

Looking for the proper way to integrate a plugin within a Vuex module or plain JS module. Currently using an event bus but unsure if it's the best approach. Any guidance would be appreciated. Plugin1.plugin.js: const Plugin1 = { install(Vue, optio ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

The personalized confirmation dialog is experiencing malfunctions

I have designed my own custom dialogs using Bootstrap and jQuery, such as Alert and ConfirmDialog. Here is a sample: http://jsfiddle.net/eb71eaya/ The issue I am facing is that in the callback function, I make an AJAX call. If it returns true, I want to ...

What is the significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...