最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace null value with a string in an array which is a JSON output - V2.0 - Stack Overflow

programmeradmin1浏览0评论

I was trying to replace the null value that I get through a JSON after submitting a form by a String value like 'n/a' or 'not specified'. I have added few lines as @Winter Solider suggested which is mented below to check null value and replace it but the code I added doesn't work. And idea?
-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) {
    // here I am trying 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.";
  }
}

I was trying to replace the null value that I get through a JSON after submitting a form by a String value like 'n/a' or 'not specified'. I have added few lines as @Winter Solider suggested which is mented below to check null value and replace it but the code I added doesn't work. And idea?
-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) {
    // here I am trying 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.";
  }
}
Share Improve this question edited Aug 5, 2021 at 12:34 Audwin Oyong 2,5313 gold badges19 silver badges36 bronze badges asked Nov 22, 2016 at 18:42 alastalast 152 silver badges8 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Observation: You are using filter unnecessarily as it creates another array on valueArray array. Instead you can use forEach. and

Solution:

if (valueArray.length) { // It'll do the same job as 'valueArraylength > 0'
    // here I am trying to handle the null value issue
    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) {
        // output search results to the dom
        renderSearchResults(JSON.parse(data), document.getElementById('searchResults'));
    });
}

Hope this helps :)

  • Your null values are getting filtered out even before you execute the map. Whenever there is a null value from element you are looking up, it ends up being filtered out.
  • So you are better off not using the filter. Modify your code based on other answers. Switch to each or something.
  • Though I have 9 inputs, it only prints 8

See the below code

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 what you need at the end of null check?
  • If you are trying to replace the null string value with n/a, this is perhaps what you'll need to do
  • Edited the code to refelct "" 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 trying to handle 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 rest of your code
}

It works correctly for me. Perhaps you need to check for the empty string as well?

var valueArray=[5,6,7,8,null,3,4,5,0,0,0,9,''," "]
            for (var i = 0; i < valueArray.length; i++) {
                if (valueArray[i] === null || valueArray[i] === ' ' || valueArray[i] === '') {
                    valueArray[i] = 'n/a';
                }
              console.log(valueArray[i]);
            }

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
}];
for (var i = 0; i < valueArray.length; i++) {
                            Object.keys(valueArray[i]).forEach(function (field) {
                            if(valueArray[i][field] == null){
                            valueArray[i][field] = "";
                            }
                            })                   
                    };
                    console.log(valueArray);

发布评论

评论列表(0)

  1. 暂无评论