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

What is the best way to extract individual objects from several arrays and consolidate them into a single array?

Currently, I have a collection of objects stored in a variable called listOfObjects. They are not separated by commas because I utilized the Object.entries method to extract these values from another array. console.log(listOfObjects) outputs { q: 'L ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

6 Steps to Extract Data from a POST Request Using JavaScript

I have a form that includes a text field and a select field. When the form is submitted, I am posting it. Can someone guide me on how to extract the form data on the server using JavaScript? <form id="createGameForm" action="/createGame" method="post" ...

Using Angular and Jade to pass an array from a controller to script tags

I am trying to figure out how to access an array in my controller and display it accurately within the <script> tags in my jade template. For instance: Controller.js $scope.myArray = ["item1","item2"]; Within my index.jade: script. var clien ...

Enhancing React Native experience by dynamically editing array elements

This code block defines the state of my program, including an array: this.state = { arr: [{ arrid: 0, arrEmail: '', arrName: '', arrPhone: '' }], id: 0, email: "", isChecked: true, name: "", phon ...

What is the best way to implement lazy loading of images that have not been downloaded in a JavaFX WebView?

Currently, I am in the process of developing an email client application using JavaFX WebView to showcase email HTML files. In order to enhance its responsiveness and speed, my goal is to display inline images in emails as they are downloaded locally. Duri ...

How to link AngularJS controller from a different module in routing

My current project involves creating a complex app with a structured design: Each module is organized in its own folder structure, including controllers, directives, and more. Within each folder, there is an index.js file along with other files for separ ...

What is the best way to link optional and undefined paths in AngularJS routing?

When it comes to AngularJS routing, I have a question. How can we combine the use of a star (*) to match paths with slashes and a question mark (?) to match optional paths? Specifically, I am looking to match both /admin/tasks and /admin/tasks/arbitrary/pa ...

Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist. However, instead of adding the new item only once, it ends up being added multiple times. What would be ...

"The function within the Sails.js model is not properly returning a value when rendered

Within my Sails.js application, I am currently attempting to retrieve the total number of users that have been approved in my database and utilize this count variable within my view by employing the count() query. Below is the snippet of code present in my ...

Encountering an issue with resolving 'create-react-class'

I have some files with hobbies listed in Data.js. I am attempting to add these hobbies and display them in a list format within my App.js file. However, I keep encountering an error stating that the create-react-class module cannot be found. Does anyone k ...

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

Using Reactjs to automatically populate text into a React-Select Input field

I have implemented react-select in my project. Sometimes, I encounter the need to update my react-select input field without directly interacting with it (such as injecting text into it). However, I am unable to find a proper way to achieve this based on ...

Hide in certain zones, contextual menu

I recently discovered how to create my own context menu with links based on the div clicked (check out here for more details). However, I am facing an issue now. I am struggling to prevent the context menu from appearing above the specific div boxes where ...

Angular's two-way binding feature allows the use of a variable as a string without directly assigning it to

Sample HTML code: <div tile-component included-svg='::installController.installUpdatesSvg'></div> Install controller: **A scope variable named 'installUpdatesSvg' is defined** this.installUpdateSvg = 'xyzSvg'; ...

Unable to modify existing attributes in a sails.js model

I'm new to sails.js and I have a question about adding fields to an existing model in Sails.js. Here is the current model: module.exports = { attributes: { id: { columnName: 'id', type: 'integer&apos ...

Scrolling to the bottom of the page triggers jQuery to load additional content

Is your jQuery script not working properly when attempting to load more content upon reaching the bottom of the page? It seems to be functional on Safari/iPad and Android Mozilla browsers, but encountering issues on default Android and Chrome browsers. ...

Using a prop array as v-model in a Vue JS CheckBoxGroup implementation

Struggling to create a reusable CheckBoxGroup component with a prop array as v-model. I checked out the vuejs guide at https://v2.vuejs.org/v2/guide/forms.html#Checkbox which uses the v-model array in the data of the same component. However, this approach ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

Searching for a cake in CakePHP with autocomplete functionality

$( "#skills" ).autocomplete({source: function(request, response) { $.getJSON("http://server/current/indrealestates.com/properties/autosuggesthome/",{ term:request.term ,extraParams:$('#property_id').val()}, response ); }, ...