elimination of nonexistent object

How can I prevent releasing data if two attributes are empty?

const fork = [
  { from: 'client', msg: null, for: null },
  { from: 'client', msg: '2222222222222', for: null },
  { from: 'server', msg: 'wqqqqqqqqqqqq', for: 'data/64.....' }
];

console.log(message)

These examples show three entries that are consistently updated. However, there are more entries like these.

I'm looking to only send data if both attributes are not empty, and avoid sending any values that are null.

const fork = [
  { from: 'client', msg: null, for: null }, // remove entire line
  { from: 'client', msg: '2222222222222', for: null }, // remove 'for'
  { from: 'server', msg: null, for: 'data/64.....' } // remove 'msg'
];
console.log(message)

Answer №1

You have the option to apply a filter to the array and then use the map function on the resulting elements.

const
    fork = [{ from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqqqqqq', for: 'data/64.....' }];
    result = fork
        .filter(o => ['msg', 'for'].some(k => o[k] !== null))
        .map(o => Object.fromEntries(Object
            .entries(o)
            .filter(([, v]) => v !== null)
        ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

const fork = [
  { from: 'client', msg: null, for: null },
  { from: 'client', msg: '2222222222222', for: null },
  { from: 'server', msg: 'wqqqqqqqqqqqq', for: 'data/64.....' }
];

const filteredFork = fork.map(item => {
  if (Object.values(item).filter(i => i === null).length > 1) return null;
  const cleanedObj = { ...item };
  for (const key in cleanedObj) {
    if (cleanedObj[key] === null) {
      delete cleanedObj[key];
    }
  }
  return cleanedObj;
}).filter(item => item !== null);

console.log(filteredFork)

Answer №3

Utilizing the reduce technique

const branches = [
  { from: "client", msg: null, for: null },
  { from: "client", msg: "2222222222222", for: null },
  { from: "server", msg: "wqqqqqqqqqqqq", for: "data/64....." },
];

const result = branches.reduce((accumulator, current) => {
  const object = { from: current.from };
  ["msg", "for"].forEach((key) => (current[key] !== null && (object[key] = current[key])));
  return Object.keys(object).length > 1 ? accumulator.concat(object) : accumulator;
}, []);

console.log(result);

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 Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below: import React from 'react'; import styled f ...

Altering the text of dropdown items prior to the ASP.NET autopostback

Recently, I inherited a project from a client that is plagued with some irritating issues. One particular problem involves a dropdown menu that triggers an autopostback event upon selection change, inserting the selected text into a T-SQL query. The troubl ...

Different strategies for displaying a singular pie chart on multiple pages

I have implemented a pie chart on an HTML page and now I want to display this chart on multiple other HTML pages. Below is the JavaScript code for creating the pie chart: function piechart() { var chart; var legend; ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

What is the best way to retrieve the matching keys for a specific key in a multidimensional array?

In my PHP code, I have a multidimensional array structured as shown below: $array = array ( 0 => array ( 'date' => '2013-03-25', 'name' => 'Bob', 'time' => '11&apo ...

Inserting data into a JavaScript database

When attempting to add a new row to a datatable and submit it to a JSP for database insertion, an error is encountered. The error message reads: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the r ...

Javascript if-else is malfunctioning

I am having difficulty running the code below which contains if statements. I have tried removing some parts of it, but still can't get the alert to show up. Any advice would be highly appreciated. Thank you. <!DOCTYPE html> &l ...

What is the best way to generate dynamic components on the fly in ReactJS?

Could you please guide me on: Techniques to dynamically create react components, such as from simple objects? Is it possible to implement dynamic creation in JSX as well? Does react provide a method to retrieve a component after its creation, maybe b ...

App.post is returning a set of empty curly braces as the response

I am currently working on an express.js application that retrieves data from a MySQL database and displays it on the screen. I am also trying to implement an insert functionality so that I can add data to the database via the browser. However, when I post ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

Streaming data from BigQuery to the front-end using Express

Trying to extract a query from BigQuery and stream it to the frontend has been quite a challenge. In the Node.js environment with Express, one would assume it should look something like this: app.get('/endpoint', (req, res) => { bigQuery.cr ...

Enhancing Selectpicker options in Angular using data fetched from a web service

Having trouble with updating a selectpicker element within a subscribe method. I've included the code snippets below: Here is my HTML code: <div class="form-group col-md-2 pull-right"> <label for="city">City</label> <select ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

After reloading the page, Nuxt dynamic routes are displaying a 404 error

Hey there! I'm currently diving into a project that involves using nuxt js, and it's all new to me. I've set it up in spa mode without any modifications in the nuxt config file, just sticking with the default settings. Here's how I&apos ...

Transforming jQuery object into HTML code

I need assistance with a JavaScript task where I am trying to parse and replace an item within an HTML string, but then struggling to convert it back to a string. Specifically, I am having difficulty turning the new jQuery object back to HTML. var compile ...

Coordinating numerous AJAX requests in Angular with the help of Restangular

I am currently working on an Angular application that relies on $scope references to update the view using a factory singleton that exposes model and state objects. The challenge I face is ensuring that multiple AJAX calls (using Restangular) made by the f ...

Zoom feature available on various images

My current setup includes one main image and multiple thumbnails that can be clicked to change the main image. The issue I encountered was when using jqzoom on the main image, the zoomed image would go blank after changing. After researching on stack overf ...

Encountering issues trying to display state value retrieved from an AJAX call within componentDidMount in React

I recently implemented an AJAX call in my React application using Axios, but I am a bit confused about how to handle the response data. Here is the code snippet that I used: componentDidMount() { axios.get('https://jsonplaceholder.typicode.com/us ...