What is the best way to add a null property from an object into an array?

I am currently working with an array of objects and have the need to remove any empty properties within the objects.

For instance:

var quotes = [
{
    quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
    source: "Winston Churchill",
    citation: "",
    year: "29 May 1919",
    place: ""
},
{
    quote: "Learn while you live",
    source: "",
    citation: "X",
    year: "1950",
    place: ""
}];

I have multiple objects like these with randomly empty properties.

What I want to achieve is to display only the properties that are not empty on the page.

My approach involves looping through the objects to identify and remove the empty properties using indexOf() and splice():

function findEmptyProp(quotes) {
   for (prop in quotes) {
     if(quotes[i].children === '') {
        return indexOf(quotes[i]);
        quotes.splice(i, 1);
}}}

Any assistance would be greatly appreciated.

Answer №1

When working with arrays, the splice method is commonly used. However, when dealing with objects, the delete method must be utilized.

One approach to handle this situation is outlined below:

var quotes = [{
  quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
  source: "Wyston Churchill",
  citation: "",
  year: "29 May 1919",
  place: ""
}, {
  quote: "Learn while you live",
  source: "",
  citation: "X",
  year: "1950",
  place: ""
}];

quotes.forEach(function(o){
  for (var k in o){
    if(o.hasOwnProperty(k) && isEmpty(o[k])){
      delete o[k];
    }
  }
});

function isEmpty(val){
  return val === undefined || 
    val === null || 
    (typeof(val) === "object" && Object.keys(val).length === 0) || 
    (typeof(val) === "string" && val.trim().length === 0)
}

console.log(quotes)

Adding to the insight provided by deceze, additional cases for considering values as empty have been included. It is also recommended to verify the hasOwnProperty method for updating properties of the object itself.

Answer №2

Just a heads up: The Object.keys(obj) method is useful for extracting an array of an object's keys. For example,...

var objectArray = [
  {
    key1: '1',
    key2: '2',
    key3: ''
  },
  {
    key1: '1',
    key2: '',
    key3: '3'
  },
  {
    key1: '',
    key2: '2',
    key3: '3'
  }
];

objectArray.forEach(function(obj) {
    /* 'obj' represents each object in 'objectArray' */
    Object.keys(obj).forEach(function(key) {
        /* 'key' represents each key in 'obj' */
        if (obj[key] === '') delete obj[key];
    });
});

/* testing objectArray */
objectArray.forEach(function(obj) {
    console.debug(obj);
});

/** =>
    Object { key1: "1", key2: "2" }
    Object { key1: "1", key3: "3" }
    Object { key2: "2", key3: "3" }
**/

Utilizing array methods like .forEach(), .filter(), .sort(), .reduce(), and .map() on Objects can be extremely beneficial.

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

Discovering the highest value in the final row of a two-dimensional array

I'm currently working on extracting the maximum value from the last column of a specific array and printing it out. Despite attempting to utilize the Double.max() method, I have encountered issues with it not functioning correctly for this particular ...

AngularJS Class Confirmation Button

I'm currently working on implementing a "confirm" button for users of my website to see after clicking a specific button, using an angularJS class. Below is the code snippet I have written: class TodosListCtrl { constructor($scope, $window){ $s ...

Push the accordion tab upwards towards the top of the browser

I am working on an accordion menu that contains lengthy content. To improve user experience, I want to implement a slide effect when the accordion content is opened. Currently, when the first two menu items are opened, the content of the last item is disp ...

How to effectively utilize wrapAsync in MeteorJS when working with callbacks in the vzaar API?

Issue to Resolve: My current challenge involves retrieving an uploaded video ID asynchronously from an API in order to incorporate it into my code once the video upload process is completed. Unfortunately, I am encountering issues where the returned value ...

Switch between 2 buttons by using ng-class in Angular JS

In a button group, one button is designated as "active" by the ng-class attribute (either myCtrl.onactive or myCtrl.offactive) <div class="btn-group pull-right"> <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.ch ...

Can a method be generated through the use of an argument?

Imagine having two distinct functions below: def do1(x, y): return x + y def do2(x, y): return x - y You could define a class in the following manner: class foo(object): def __init__(self, func): self.func = func abc = foo(func=do1 ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Error in Node.js Socket.io: The disconnect event is being triggered before the connect event

When the client reconnects after a network drop, the disconnect event is triggered on the server. Client code: var url ='192.168.1.101', port = '80', socket = io.connect('http://' + url + ':' + port, { &apo ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

Obtain serialized information from php using ajax

I am currently working with a php script that returns serialized data. I am trying to retrieve this data using the $.ajax() method from jQuery 1.7. You can find an example here. $.ajax({ url: 'http://input.name/get.php?do=lookup' + '&am ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

Troubleshooting Automatic Scrolling Problems in React Virtualized

In my project utilizing react-virtualized v-9.21.2 to showcase a list, a problem arises when adding a new item. I employ a method of clearing the cache and updating the listKey to enable auto resizing the height. However, this results in an undesired behav ...

What is the best way to change the first letter of a string to uppercase in JavaScript?

Creating a form with 10 textboxes and one button, I want the first letter of any text entered into a textbox to be capitalized when the user loses focus on that specific field. To achieve this functionality, JavaScript seems like the most suitable option. ...

Upgrade your project from Angular 5 to Angular 9 using webpack

I want to share my experience, not ask a question! To upgrade dependencies in package.json: -Update all Angular dependencies to version 9 -Add these dependencies: "@angular-devkit/build-angular": "^0.900.4", "@angular-builders/cu ...

Angular Js powered admin control panel

Explore the SB Admin Angular by Start Angular My current project involves setting up an admin dashboard on a Windows system. However, I have encountered some issues during the installation process using npm install An error message can be found here ...

Issue with inserting data into MySQL database using Node.js (JavaScript)

I am attempting to utilize the insert function but keep encountering an error. I want to add a user's name to the user table. The function I am using is: function insert(tableName, toField, value){ connection.connect(); var queryString = "i ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Converting an Array into a String

Struggling to transfer a MYSQL associative array into a PHP array and encountering the following error: Error message: Array to String type conversion Code snippet: $sql="SELECT brand_id FROM brand WHERE (name IS NOT NULL OR name != '') AND ...

A function that checks if all numbers from 0 to n-1 are present in the given array, having a time complexity of O(n) and returning either 0 or 1

UPDATE: I accidentally omitted that I do not wish to assign another temporary array. I am tackling a challenge in C, where I am tasked with: Given an array 'a' and its size 'N', it is known that all elements in the array fall within th ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...