Upgrade to V2.0: Substituting empty values with a specified string within a JSON formatted array

After submitting a form and receiving null values through JSON, I wanted to replace them with String values like 'n/a' or 'not specified'. Even though I followed @Winter Soldier's suggestion and added code to check for null values and replace them, it doesn't seem to be working. Any thoughts on how to fix this?
-thanks

function submitFormFunction() {
  //document.getElementById("form").submit();
  var valueArray = [
    {
      'label': 'contractId',
      'value': document.getElementById('ContractId').value
    },
    {
      'label': 'title',
      'value': document.getElementById('ContractTitle').value
    },
    {
      'label': 'minYear',
      'value': document.getElementById('MinYear').value
    },
    {
      'label': 'maxYear',
      'value': document.getElementById('MaxYear').value
    },
    {
      'label': 'terminal',
      'value': document.getElementById('Terminal').value
    },
    {
      'label': 'location',
      'value': document.getElementById('Location').value
    },
    {
      'label': 'theme',
      'value': document.getElementById('Theme').value
    },
    {
      'label': 'construction',
      'value': document.getElementById('Construction').value
    },
    {
      'label': 'asBuilt',
      'value': document.getElementById('AsBuilt').value
    }
  ].map(function (param) { return param.label + '=' + param.value; });
        
  if (valueArray.length) {
    // attempt to handle the null value issue as suggested by Winter Soldier 
    for (var i = 0; i < valueArray.length; i++) {
      if (valueArray[i].includes("null")) {
        valueArray[i] = valueArray[i].replace("null", "n/a");
      }
    }
  
    console.log(valueArray)
    console.log(valueArray.join('&'));
    //var queryStr = JSON.stringify(valueArray.replacer);
    var queryString = valueArray.join('&');
    fetch(searchUrl, '?' + queryString, function (data) {
      // output search results to the dom
      renderSearchResults(JSON.parse(data), document.getElementById('searchResults'));
    });
  } else {
      document.getElementById('searchResults').innerHTML = "Please enter a search term.";
  }
}

Answer №1

Insight: The usage of filter in the code is redundant as it generates an additional array within the existing valueArray. A more efficient approach would be to utilize forEach.

Resolution:

if (valueArray.length) { // This achieves the same outcome as 'valueArraylength > 0'
    // Here, I am addressing the issue of handling null values
    valueArray.forEach(function(value){
        if (value == null || value == "") {
          value = "n/a";
        }
    })
    //var queryStr = JSON.stringify(valueArray.replacer);
    var queryString = valueArray.join('&');
    fetch(searchUrl, '?' + queryString, function (data) {
        // Display search results on the webpage
        renderSearchResults(JSON.parse(data), document.getElementById('searchResults'));
    });
}

Hopefully, this provides some assistance :)

Answer №2

  • Before executing the map function, your null values are being filtered out automatically. If there is a null value in the element you are trying to access, it will be excluded.
  • Therefore, it would be wise to avoid using the filter method. Consider revising your code based on alternative solutions suggested by other responses. Switch to 'each' or something similar.
  • Despite having 9 inputs, only 8 of them get printed.

Check out the code snippet below:

var valueArray = [
  {
    'label': 'contractId',
    'value': 'ContractId'
  },
  {
    'label': 'title',
    'value': 'ContractTitle'
  },
  {
    'label': 'minYear',
    'value': 'MinYear'
  },
  {
    'label': 'maxYear',
    'value': 'MaxYear'
  },
  {
    'label': 'terminal',
    'value': 'Terminal'
  },
  {
    'label': 'location',
    'value': 'Location'
  },
  {
    'label': 'theme',
    'value': 'Theme'
  },
  {
    'label': 'construction',
    'value': 'Construction'
  },
  {
    'label': 'asBuilt',
    'value': null
  }
].filter(function (param) { return param.value; })

console.log(valueArray)
console.log(valueArray.length)

EDIT:

  • Is this the final check you need for handling nulls?
  • If you want to replace null string values with "n/a," here's how you can achieve that:
  • I've made changes to the code to address the empty string check

var valueArray = [{
  'label': 'contractId',
  'value': 'ContractId'
}, {
  'label': 'title',
  'value': 'ContractTitle'
}, {
  'label': 'minYear',
  'value': 'MinYear'
}, {
  'label': 'maxYear',
  'value': 'MaxYear'
}, {
  'label': 'terminal',
  'value': 'Terminal'
}, {
  'label': 'location',
  'value': 'Location'
}, {
  'label': 'theme',
  'value': ''
}, {
  'label': 'construction',
  'value': 'Construction'
}, {
  'label': 'asBuilt',
  'value': null
}].map(function(param) {
  return param.label + '=' + param.value;
});
if (valueArray.length) {
  // Here I am attempting to resolve the null value issue.
  for (var i = 0; i < valueArray.length; i++) {
    if (valueArray[i].includes("null") || !valueArray[i].split("=")[1].length ) {
      valueArray[i] = valueArray[i].split("=")[0] + "=n/a";
    }
  }
  console.log(valueArray)
  console.log(valueArray.join('&'));
  // The remaining part of your code goes here
}

Answer №3

It is functioning correctly for me. Have you considered checking for empty strings too?

var numberArray=[3,8,null,2,'',0,6,9]
    for (var x = 0; x < numberArray.length; x++) {
        if (numberArray[x] === null || numberArray[x] === '') {
            numberArray[x] = 'unknown';
        }
        console.log(numberArray[x]);
    }

Answer №4

var values = [{
  'item': 'contractId',
  'info': 'ContractId'
}, {
  'item': 'title',
  'info': 'ContractTitle'
}, {
  'item': 'minYear',
  'info': 'MinYear'
}, {
  'item': 'maxYear',
  'info': 'MaxYear'
}, {
  'item': 'terminal',
  'info': 'Terminal'
}, {
  'item': 'location',
  'info': 'Location'
}, {
  'item': 'theme',
  'info': ''
}, {
  'item': 'construction',
  'info': 'Construction'
}, {
  'item': 'asBuilt',
  'info': null
}];
for (var i = 0; i < values.length; i++) {
                            Object.keys(values[i]).forEach(function (field) {
                            if(values[i][field] == null){
                            values[i][field] = "";
                            }
                            })                   
                    };
                    console.log(values);

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

Guide to sending a JSON from an action in ZF3

Whenever I try to send a JSON object instead of a view from an action function, I encounter a problem. The configuration in my /config/modules.config.php file is set up like this ... return [ //... 'view_manager' => [ //... ...

Accessing JSON values using path in C++

Currently engaged in a project focusing on extracting values from a Json based on the path obtained from a json schema. The goal is to retrieve the values of keys present in the json schema from the Json. Paths for value retrieval: /array/0 /boolean /nul ...

Utilize parameters in specified file in node.js

Currently, I am attempting to send variables to a file that I have imported in node.js in order to utilize them within that specific file. var myname = "Adnan"; var incfile = require('./ex.js'); My main goal is to access the myname variable wit ...

Encountering a 'next' error with Facebook Connect

I'm currently in the process of testing out the new Facebook authentication system, but I'm facing some issues with getting the login to function properly. Here's the error message I'm encountering: API Error Code: 100 API Error Desc ...

The JSON data could not be decoded because it was not in the expected format. The error occurred at line 1, column 1, character

I'm currently working on a project that involves creating a program with two clients and a server. The main goal is to send JSON data from client 1 to client 2, which client 1 has first received from the server. However, I've encountered an issue ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...

Using C++ and OpenMP to prevent false sharing in a closely looped array

I am incorporating OpenMP into my C++ code in order to enhance performance, using a straightforward example: #include <omp.h> #include <chrono> #include <iostream> #include <cmath> using std::cout; using std::endl; #define NUM 100 ...

Creating a robust system for resetting passwords using the powerful combination of Django Rest Framework, Serializers, and Vue.js

I am currently in the process of implementing a reset password feature, but I am struggling to find comprehensive tutorials on how to do so using DRF and Vue.js. My approach involves utilizing serializers for data passing without incorporating HTML views. ...

Combining react-draggable and material-ui animations through react-transition group: a comprehensive guide

Trying to incorporate react-draggable with material-UI animations. One approach is as follows: <Draggable> <Grow in={checked}> <Card className={clsx(classes.abs, classes.paper)}> <svg classN ...

Unable to populate data in dropdown using Angular framework?

My datatable displays elements along with an edit button. At the top of the page, there is also an add button. The purpose of the add button is to add elements to the list, while the edit button allows for editing the data in a particular row. When the u ...

What is the best way to implement an undo-list using arrays?

My current project involves creating a paint program in JavaScript, and I am aiming to implement an undo function rather than just an eraser. How can I store events in an array and then enable the deletion of each event individually? I have a dropdown men ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

Building a breadcrumb navigation system using a tree class in PHP

After receiving an API SOAP response containing a list of categories in a class format resembling an array structure with CatID, name, parentID, and level, I am looking for the most efficient method to convert this information into an array of breadcrumbs ...

Retrieving information from a JSON string can be done with or without using the JSONObject

I have a Java String containing the following JSON code: String str = {"posts":[{"key":"key1","value":"x"},{"key":"key2","value":"0"},{"key":"key3","value":"y"}]} Is there a way to extract the values from the string using JSONObject, or should I stick wi ...

Transform an object into a corresponding object of a different type using json.net serialization

I recently encountered a problem similar to the issue discussed in this thread on Stack Overflow, but I'm still facing errors. My scenario involves working with 3 classes: public class Class1 { public string[] P2 { get; set; } } public class Cl ...

Utilizing AngularJS, implement ng-form and ng-repeat to seamlessly handle input validation and submission actions

Angular 1.6.2 I am experimenting with iterating over elements of a collection inputted by the user, checking their validity, and enabling the submit action if validation passes. I have tried using ng-form for this purpose and have come up with two differ ...

The div keeps appearing multiple times while the button remains inactive

In order to create a password confirmation form with validation, you need to have two input fields - one for entering a new password and another to confirm the password. The goal is to display a message saying "please enter the password above" below the ...

Extending a type by adding properties from separate files using TypeScript

I am faced with a situation where I have a file containing either a type or interface variable (all of which are exported), and I need to add new properties to this variable from different files without using extends. Essentially, making changes to the sam ...