Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they present new challenges that I am struggling to overcome.

Thanks to @kooiinc's response, my code now looks like this:

var grants = [
    { id: "p_1", location: "loc_1", type: "A", funds: "5000" },
    { id: "p_2", location: "loc_2", type: "B", funds: "2000" },
    { id: "p_3", location: "loc_3", type: "C", funds:  "500" },
    { id: "p_2", location: "_ibid", type: "D", funds: "1000" },
    { id: "p_2", location: "_ibid", type: "E", funds: "3000" }
];
var projects = [];
grants.map(
function (v) {
    if (!(v.id in this)) {
        this[v.id] = v;
        projects.push(v);
    } else {
        var current = this[v.id];
        current.type = [v.type].concat(current.type);
        current.funds = [v.funds].concat(current.funds);
    }
}, {});

... resulting in the desired output (type and funds combined into sub-arrays, while other properties remain unchanged):

[
    { "id": "p_1", "location": "loc_1", "type": "A", "funds": "5000" },
    { "id": "p_2", "location": "loc_2", "type": ["E","D","B"], "funds": ["3000","1000","2000"] },
    { "id": "p_3", "location": "loc_3", "type": "C", "funds": "500" }
]

However, when certain objects contain undefined key values, the result includes nulls in the arrays as shown below (observe the type array):

[
    { "id": "p_1", "location": "loc_1", "type": "A", "funds": "5000" },
    { "id": "p_2", "location": "loc_2", "type": ["E",null,null], "funds": ["3000","1000","2000"] },
    { "id": "p_3", "location": "loc_3", "type": "C", "funds": "500" }
]

(For a demonstration, refer to this fiddle.)

I attempted to remove these null values using methods like the ones mentioned here or here, but unfortunately, none of them seemed to work effectively despite being implemented at different stages in my code. These methods did not produce any errors, but they simply did not eliminate the null values.

Is there a way to exclude undefined keys during the mapping process itself?

Update: Some object keys may have no values at all, only containing [null,null,null], while others might have some filled values alongside null entries such as ["E",null,null]. The aim is to filter out all null items, subsequently removing the entire key if it contains no remaining values.

Answer №1

Give this approach a try:

grants.map(
 function (item) {
    if (!(item.id in this)) {
        // => initialize if empty
        item.type = item.type || [];
        item.funds = item.funds || [];
        this[item.id] = item;
        projects.push(item);
    } else {
        var current = this[item.id];
        current.type = item.type ? [item.type].concat(current.type) : current.type;
        current.funds = item.funds ? [item.funds].concat(current.funds) : current.funds;
    }
 }, {});

By using this method, the result will not display empty values.

Answer №2

One potential solution is to check for the existence of both the type and funds properties before inserting or updating the element.

a.type && a.funds && ...

var grants = [
        { id: "p_1", location: "loc_1", type: "A", funds: "5000" },
        { id: "p_2", location: "loc_2", funds: "2000" },
        { id: "p_3", location: "loc_3", type: "C", funds: "500" },
        { id: "p_2", location: "_ibid", funds: "1000" },
        { id: "p_2", location: "_ibid", type: "E", funds: "3000" }
    ],
    project = [];

grants.forEach(function (a) {
    a.type && a.funds && !project.some(function (b, i) {
        if (a.id === b.id) {
            project[i].type.push(a.type);
            project[i].funds.push(a.funds);
            return true;
        }
    }) && project.push({ id: a.id, location: a.location, type: [a.type], funds: [a.funds] });
});
document.write('<pre>' + JSON.stringify(project, 0, 4) + '</pre>');

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

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. Step 2: Inside the attribute-users component, an HTTPS GET request is made to re ...

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

Transforming the DOM using jQuery

I am looking to manipulate the DOM using jQuery. This is the initial source code: <td class="name"><a href="position_details.php?x=-109&amp;y=95">21</a> </td> <td class="name"><a href="position_details.php?x=-109& ...

What are the best methods for cropping SVG images effectively?

Is it possible to crop a large SVG background that has elements rendered on top of it so that it fits the foreground elements? I am using svg.js but have not been able to find a built-in function for this. Can an SVG be cropped in this way? ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Create a form with two submission buttons along with a captcha verification system

I'm currently developing a booking page form that requires a unique functionality. I need a single form where clients can enter their information, followed by two submit buttons at the bottom. The first button should hold their reservation for 72 hour ...

Encasing the Angular 2 component template in a <div> tag

Currently, I have a parent component managing multiple child components. My goal is to enclose each child component's template with a *ngIf directive for conditional rendering. The number of children in the parent component can vary. Here is an examp ...

Encountering the error message "Uncaught TypeError: Cannot read property 'addEventListener' of null with querySelector

I attempted using getElementsByClassName but encountered the same error, which is peculiar. I had to change <p id="trigger-overlay"> in my HTML to <p class="trigger-overlay"> error function toggleOverlay(){alert('fire');}; var tri ...

Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs? I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is ...

Flipping the camera rotation matrix in three.js

I am struggling with a scenario involving objects and a camera being controlled by a trackball. Whenever I add a new object to the main object, I want it to maintain its original orientation regardless of how the camera has moved around. For instance, with ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Produ ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

The execution of consecutive Ajax requests encounters issues in the Google Chrome and Safari browsers

I am facing an issue where I encounter a problem displaying a sequence of dialogue or AJAX results that depend on each other. For instance, when a user clicks to send a message, it triggers an ajax call, which opens a dialogue box. The user fills out the f ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...