In certain arrays, blank entries are stored separately in a designated section reserved for null values

var dataList = [ 
                 { date: '2019-08-08', class: null, users: 21 },
                 { date: '2019-08-08', class: 'lower', users: 21 },  
                 { date: '2019-08-08', class: 'upper', users: 3}
                 { date: '2019-08-08', class: 'middle', users: 5}

               ];

If any element in the array has a key with the value null, I would like to change it to be stored under the "Others" key instead. Each array contains multiple dates and one null value.

Replace null with "Others"
var dataList = [ 
                { date: '2019-08-08', class: 'Others', users: 21 },
                { date: '2019-08-08', class: 'lower', users: 21 },  
                { date: '2019-08-08', class: 'upper', users: 3}
                { date: '2019-08-08', class: 'middle', users: 5}
              ];

Answer №1

Utilizing a forEach iteration

var dataList = [ 
                 { date: '2019-08-08', class: null, users: 21 },
                 { date: '2019-08-08', class: 'lower', users: 21 },  
                 { date: '2019-08-08', class: 'upper', users: 3},
                 { date: '2019-08-08', class: 'middle', users: 5}

               ];
dataList.forEach(function(item){
if(item.date==null)
item.date='Others'
if(item.class==null)
item.class='Others'
if(item.users==null)
item.users='Others'
})
console.log(dataList)

Answer №2

To implement this functionality, utilize the map function as demonstrated below:

 

const data = [ 
             { date: '2020-12-15', category: null, count: 32 },
             { date: '2020-12-15', category: 'low', count: 45 },  
             { date: '2020-12-15', category: 'high', count: 10},
             { date: '2020-12-15', category: 'medium', count: 22}

           ];

const result = data.map(({ category: cat, ...rest }) => ({ category: cat == null ? "Other" : cat, ...rest }));

console.log(result);

Answer №3

Implementing the array.map() method would be the best approach:

By using the map() function, you can generate a new array by applying a specified function to each element in the original array.

var dataList = [ 
                 { date: '2019-08-08', class: null, users: 21 },
                 { date: '2019-08-08', class: 'lower', users: 21 },  
                 { date: '2019-08-08', class: 'upper', users: 3},
                 { date: '2019-08-08', class: 'middle', users: 5}

               ];
               
let newList = dataList.map( (obj) => obj.class == null? { ...obj, class: "Other" } : obj );

If you require checking for any key in obj rather than just the class key, please indicate here so that I can modify my response accordingly.

Answer №4

This piece of code is quite straightforward:

dataList = dataList.map(x => {
    x.class = x.class || "Others";
    return x;
})

var dataList = [ 
                 { date: '2019-08-08', class: null, users: 21 },
                 { date: '2019-08-08', class: 'lower', users: 21 },  
                 { date: '2019-08-08', class: 'upper', users: 3},
                 { date: '2019-08-08', class: 'middle', users: 5}

               ];
               
dataList = dataList.map(x => {
    x.class = x.class || "Others";
    return x;
})

console.log(dataList)

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

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Having difficulty consolidating the data received from the Twilio API

My goal is to retrieve billing data from the Twilio API and store the fetched value in a variable for display on my web application. Despite my attempts with async and await, I've encountered difficulties getting it to function as intended. const twil ...

Issue with filtering tasks in a Task Tracker application

Hey there! I'm new to JavaScript and I've been working on a todo app. Everything seems to be running smoothly except for the filter function, which I just can't seem to get working no matter what I try. I previously had a similar app with ma ...

Tips for refreshing a nested state in React

Currently, I am facing an issue with updating a nested value in a React state. My goal is to update data that is deeply nested, specifically 3 levels deep. Let me provide you with the state structure that contains the data: const [companies, setCompanies ...

How can I efficiently make a GET request to the server using just plain JavaScript?

What is the most efficient method for making a GET request to the server using pure JavaScript? ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...

Creating an image slideshow with a looping JavaScript array: Step-by-step guide

One issue with the program is that when it runs, only the last array value image is displaying on the screen while the other images are not. Below is the HTML code: <img id="mg" alt="image not found"> And here is the JavaScript code: var images=[ ...

Adding choices to a dropdown menu

This issue is connected to the question about Adding options to a <select> using jQuery?, but it focuses on a different aspect. The problem I'm facing is the inability to add option elements to a select in IE8. Interestingly, when switching the ...

The complete rendering of angular-google-maps is only achieved after resizing the browser

<ui-gmap-google-map center="{latitude: 43.100187, longitude: -77.6329959}" zoom='8'> </ui-gmap-google-map> https://i.sstatic.net/9F2eb.jpg All necessary files were loaded via bower and the dependency was added t ...

AngularJS: when only one line is visible, the other remains hidden

Issue with AngularJS: Only One Line Displaying Instead of Both I am encountering an issue with my AngularJS code where only one of the elements is displaying on my page. function Today($scope, $timeout) { $scope.now_time = 0; (function update() { ...

What is the procedure for assigning values to an array?

I'm currently in the process of creating a hamburger object that needs to include an array of toppings and other properties. However, I'm encountering a compilation error whenever I attempt to assign values to the toppings array for each object. ...

Create a function called plagiarismChecker that requires two parameters: an array containing the students' responses, and a small snippet of text

Write a custom function called detectPlagiarism that accepts two parameters: an array of student responses and a snippet of text to check for plagiarism. The function should return true if any of the essay question answers contain the specified text, and f ...

"When the focus is on, the DateTimePicker component in react widgets will automatically

Embarking on my journey with React, I have a reusable DateTime component defined as follows: interface IProps extends FieldRenderProps<Date, HTMLElement>, FormFieldProps {} const DateInput: React.FC<IProps> = ({ input, width, plac ...

"Exploring the Power of Logarithmic Slider with Vue and Quasar

I'm currently working on a project utilizing Vue 2 and Quasar 1, where I am attempting to develop a logarithmic slider. Initially, I managed to create a basic example using a native input slider in this code pen: https://codepen.io/tonycarpenter/pen/Z ...

using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling ...

How can we incorporate a mesh that is loaded locally into the canvas created by Three.js in order to showcase it?

Greetings! Thank you for taking the time to read this inquiry: Currently, I am delving into the world of Three.js and have encountered an intriguing hurdle: I have successfully mastered the process of loading local NRRD files in plain HTML/JavaScript usi ...

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

Perform an AJAX request to validate the delete action before finalizing it

My website features a Telerik grid, which essentially represents a table on a page. Within this Telerik grid, there is a column dedicated to deleting records. Initially, when a user clicked on the delete link, a javascript confirm dialog would pop up. If ...