I aim to utilize lodash filter to swap out any null values with zero

let x = [{'abc': 1, 'qwe':2},{'abc': 2, 'qwe':2},{'abc': 5, 'qwe':null}, {'abc': 4, 'qwe':null}],

let result =  _.chain(x)
                _.groupBy(qwe)
                _.map((value, key) => ({
                 name: key,
                 data: _.map(_.filter(value, item => {
                 return item.qwe;
})
                  'qwe'
                 )
               })).value()
              })

output is:

qwe:[2,2,5]

Expected output is:

qwe:[2,2,5,0, 0]

Answer №1

If you're not specifically looking for "loadash", consider using the "map" method along with logical operators like "||" or "??".

let items = [{'abc': 1, 'qwe':2},{'abc': 2, 'qwe':2},{'abc': 5, 'qwe':null}, {'abc': 4, 'qwe':null}];


const getValue = (arr, key) => arr.map((item) => (item[key] || 0));

console.log(getValue(items, 'qwe'));

Answer №2

To convert null values to a specific value (in this case 0), simply use the `||` operator while mapping.

let a = [
  { abc: 1, qwe: 2 },
  { abc: 2, qwe: 2 },
  { abc: 5, qwe: null },
  { abc: 4, qwe: null },
];

let res = _.chain(a)
  .map("qwe")
  .map((v) => v || 0)
  .value();

console.log(res);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7dbd8d3d6c4dff783998680998587">[email protected]</a>/lodash.min.js"></script>

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

Checking if a Double variable is null can be done using the following method

When I access an endpoint and receive JSON data, I iterate through the object and assign the value to a double field. Occasionally, this field will be null. How should I address this null case in my code? Currently, it looks like this: double scanning_ris ...

When applying the OWASP ESAPI encodeForHTMLAttribute method, I noticed that symbols are being rendered as their corresponding HTML entity numbers instead of the actual symbols

I recently started exploring OWASP ESAPI for preventing XSS and integrating the JavaScript version into my application. As per Rule #2 in the XSS prevention cheat sheet, it is recommended to "Attribute Escape" before inserting untrusted data into attribut ...

The Vue 3 composition API does not allow for the return of values from helper functions to components

It seems that there may be a scope issue within my helper function. I have successfully implemented the same logic in my component and it works flawlessly. I have already utilized a composable function to incorporate ref() with the variable that needs to ...

Adjust the initial letter of every word with JQ Capitalization

I am currently working with a large JSON file using JQ to filter out unnecessary elements. While I have successfully achieved this, I encountered an issue with certain values being all capitalized strings. Unfortunately, JQ does not provide a built-in func ...

How to center a div vertically in a window

I have a CSS layout that positions a div both horizontally and vertically relative to the window. It works well, but when I scroll down the page, the div stays centered as if the page hadn't moved. width:600px; height:300px; position:absolute; left:5 ...

Discovering ways to monitor Service Providers

What Currently in my AngularJS project, I am attempting to monitor certain internal functions such as angular.module and serviceProvider. How Fortunately, I have managed to keep track of calls to angular.module successfully. var moduleCalls = spyOn(an ...

Significant slowdown observed when deleting multiple objects from the Three.js scene

We are facing a challenge when dealing with large Three.js scenes that consist of many individual objects. In some cases, our scenes can contain anywhere from 25,000 to 50,000 instances of Object3D. While this may seem like a lot, we haven't found an ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

Leveraging a function for filtering in AngularJS

I have developed an application where the content filter changes depending on which button is clicked. I have managed to figure out the straightforward filters, but now I am attempting to create a filter that displays content within a specified range. Bel ...

Using Java to generate a 2D matrix by combining two 1D arrays

In the given scenario public Object[] suite = {"diamonds","hearts","clubs","spades;}; public Object[] rank = {"J","Q","K","A"}; The task is to programmatically generate: Object[][ ...

Unexpectedly, the NodeJS application experiences a crash following numerous requests

I can't seem to figure out why my Nodejs app crashes after a certain number of requests (currently 22). The issue arises with this simple get request handler: router.get('/api/docs/fetch', async (req,res) => { try{ let docs = ...

Run code once all ajax requests have been completed

Here's the code snippet I'm working with: function updateCharts() { for (var i = 0; i < charts.length; i++) { updateChart(charts[i]); } sortQueues(); } function updateChart(chart) { $.ajax({ type: "POST", ...

What is the best way to compare two fields in react?

Good afternoon, I am currently working on a datagrid using the MUI datagrid and following the MUI Guide. I have encountered an issue where I included two fields with the same name because I needed two separate columns (one for the date and one for the nam ...

What is the preferred approach in JavaScript: having a single large file or multiple smaller files?

Having a multitude of JavaScript files loaded on a single page can result in decreased performance. My inquiry is this: Is it preferable to have individual files or combine them into one JavaScript file? If consolidating all scripts into one file is the ...

Troubleshooting JSON Parsing: No data is displaying in Kilometers

As a new programmer, I am exploring the Google Matrix API. Upon receiving the response, I am trying to extract the value of "text" as "1686 km" using Json Parsing. Thank you "destination_addresses" : [ "San Francisco, Californie, États-Unis" ], ...

Can ModelMapper be utilized in Android applications?

My current project involves retrofit with GSON, and I am now considering implementing another layer of object abstraction using Modelmapper. Is Modelmapper a suitable choice for this task in my Android development? Are there any potential performance con ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

My situation involved the ajax 304 error being triggered by the use of isNumeric

$( "#withdraw" ).submit(function( e ) { $amount = $( "input[name='amount']" ).val(); if($amount != ''){ if(!isNumeric($amount)) { alert('Amount must be in numerical value!'); ...

Why isn't my lightbox able to read this specific property?

A gallery was created using both lightgallery and cycle2. Cycle is a carousel plugin while lightgallery is a lightbox gallery. Clicking on an image in the carousel opens it in the lightbox. Everything worked perfectly until a category in the carousel was ...

Store my JSON data in a separate file and then reference it in my controller

Hello, I am currently working on an AngularJS application development project. Within my JSON data, I have information structured like this: angular.module('app', []).controller('MainController', ['$scope', function($scope) { ...