Why does `_.map` result in undefined when I return `false`?

I am facing an issue with a function that maps an array using underscore. Below is the function in question:

var services = _.map(userCopy.get('services'), function (service) {
    if (service.service_selected === true) {
        return service;
    }
});

The problem arises when the conditional === false, causing undefined to be placed into services. While I can manually remove the undefined values, it is not ideal and I want to ensure proper usage of the map function. How can I resolve this issue?

Answer №1

_.map utilizes the return value of the function to generate the result. In JavaScript, if a function does not explicitly return anything, it defaults to undefined. This explains why _.map results in undefined when the condition is not met.

If what you truly require is a _.filter

var services = _.filter(userCopy.get('services'), function(service) {
    return service.service_selected === true;
});

_.filter takes a collection and a predicate function. It evaluates the predicate function for each element in the collection, including elements that return true and excluding those that return false.

Note: Another approach is to use _.matcher, combined with _.filter, like this

var isServiceSelected = _.matcher({
    service_selected: true;
});

var services = _.filter(userCopy.get('services'), isServiceSelected);

This method is beneficial when filtering based on service_selected: true occurs frequently. For one-time instances, consider using _.where as demonstrated below.


You can also utilize _.where, which only returns objects containing all specified key-value pairs, like so

var services = _.where(userCopy.get('services'), {
    service_selected: true;
});

In this case, only service objects with service_selected attribute set to true will be returned.


Demo:

function display(heading, data) {
    var json = JSON.stringify(data, null, 4);
    document.body.appendChild(document.createElement('h3')).innerHTML = heading;
    document.body.appendChild(document.createElement('pre')).innerHTML = json;
}


var data = [{
    "name": "auth",
    "service_selected": true
}, {
    "name": "authorization",
    "service_selected": false
}, {
    "name": "faltu",
    "service_selected": true
}];


display("_.filter", _.filter(data, function (service) {
    return service.service_selected === true;
}));

display("_.matcher", _.filter(data, _.matcher({
    service_selected: true
})));


display("_.where", _.where(data, {
    service_selected: true
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Answer №2

Just updated my response... Issue is resolved now!

var paramsNotProvided = _.map(requiredParams, function (value, parameter) {
    if (value) {
        if (!req.user[parameter]) {
            return parameter;
        }
    }
});

var missingParameters = _.filter(paramsNotProvided, Boolean);

Alternatively, missingParameters can be defined as:

var missingParameters = _.filter(paramsNotProvided, function (param) {
   return param !== undefined;
});

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

I've been working on a script in JavaScript to retrieve lectures for a specific day, but I'm having trouble connecting my jQuery code to it

Exploring a JavaScript function that retrieves today's lectures for a specific section of a class using jQuery. The challenge lies in implementing this array of classes on an HTML file. //function to get today var today = new Date(); var dd = today ...

The checkbox is displayed as selected after being clicked in conjunction with another checkbox

In the tree structure, there are checkboxes that behave strangely when clicked. I have already read a similar discussion here. The problem I am encountering is that when I click on an item, it gets checked but the console does not show it as checked immed ...

Execute CGI upon the loading of the page

My goal is to achieve the following: When the HTML page loads, I want to execute a CGI script written in C to call a specific function. My current approach involves using a JavaScript function in the HTML: <body onload="MyJsFunc();"> Then, in th ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...

Ensure that each of the two divs maintains a 16:9 aspect ratio, and utilize one div to fill any remaining empty space through the

This layout is what I am aiming for: https://i.sstatic.net/uZdty.png While I can achieve a fixed aspect ratio with a 16:9 image by setting the img width to 100%, I run into an issue where the height scaling of flexbox becomes non-responsive. The height re ...

Ways to automatically expand all table groupings

Currently, I am experimenting with the Material UI table that includes a group by feature. While exploring the code, I noticed that the groups can be expanded or collapsed using a click event. However, my goal is to have all groups expanded by default as s ...

Sending a JSON object as a prop from one React.js component to another

I've been attempting to pass a JSON object retrieved by calling a REST API after submitting a form with user input. While I am successful in transferring the data to another component within the same file (this component is responsible for iterating o ...

Filtering a multidimensional array in PHP can be done by using functions like array

In my PHP code, there is an array structured as follows: Array( 0 => Array( 'NDC_Date' => '2017-02-26', 'NDC_Item' => 'Night', 'NDC_Rate' => 108.00, ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

Using Vercel for a Next.js Custom Directory Configuration

Seeking guidance on deploying Next.js with Vercel, I have made changes to the structure of my Next.js project: frontend (Current Directory for Next.js) node_modules next.config.js jsconfig.json package-lock.json package.json Contents of package.json scri ...

What could be the reason for my user input not being captured and saved as variable data on the HTML webpage?

Here is the code I am working with: var g = document.getElementById("al").value; function start() { document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g); } <p id="test2">Output will be displayed here:</p> <form> ...

The correct reading of JavaScript in HTML is a common source of confusion

After creating a basic application using the code provided in a forum thread and testing it on the worker sandbox MTurk site, I noticed a peculiar issue. The application runs smoothly when following the code from the forum answer directly. However, when at ...

Include the name of the uploaded attachment in the textarea before hitting the submit button

Is there a way to automatically insert the filename into a textarea before the user submits the form? Can this be achieved using PHP or JavaScript? Thank you. <form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLea ...

Rotating around the axis of extrusion, Three.js extrudes a 2D face

I am interested in creating a twisting effect during extrusion on a shape, rotating it about the Z-axis like seen in the examples below https://i.sstatic.net/wLF2s.png and here https://i.sstatic.net/Aq7Db.png My attempt at achieving a twisted cube is o ...

When data is retrieved, the state value in Reactjs useEffect remains unchanged

I've encountered an issue while trying to set up a Protected Route in my application. The route should display only if the user is authenticated through an API call, but for some reason, the state value isn't updating correctly. Any suggestions o ...

Unable to validate file name using pug template

Hello, I've written this code snippet for a pug template: .form__group label.form__label(for='name') Name input#name.form__input(type='text', value=`${user.name}`, required, name='name&a ...

How to Get into a Nested Class in JavaScript

I'm struggling to articulate my question, but I know there's a solution out there. I have profile cards in HTML, each with the class "card" containing two numbers. My goal is to display a progress bar specific to the % relationship of these numbe ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

Experimenting with the useDebounceCallback hook through Jest testing

Currently, I am experimenting with testing debounce functionality using Jest in a component that utilizes URL parameters for search. The function handleSearch makes use of the useDebounceCallback hook from usehooks-ts (which internally uses lodash debounce ...

Import a JSON file and convert it into an array using JavaScript

I've got a json file that resembles the following: easy.txt {"top":[[1],[2,2],[2,2,3],[7,2],[2,3],[2,3],[2,2,3],[7,2],[2,2,3],[2]],"left":[[1,1],[3,3],[3,3],[1,1],[3,4],[3,4],[1,1],[3,3,2],[9],[7]],"task":[[0,0,0,1,0,0,0,1,0,0],[0,0,1,1,1,0,1,1,1,0] ...