JSFiddle - React, Tailwind, and code Playground

by Wolfgang Fahl

HTML

<a href='https://stackoverflow.com/questions/57511751/combing-replacer-and-fields-in-json-stringify'>Stackoverflow question</a>
<pre id='console'></pre>

CSS

#console {
    border-bottom: 1px solid #ccc;
    background-color: #eee;
    height: 40pc;
    font-size: 24px;
    overflow: auto;
}

JavaScript

console = {
    log: function (message) {
        var pre = document.getElementById("console");
        pre.textContent += [ message, '\n'].join(' ');
    }
};

var fieldWhiteList=['','x1','x2','children'];

let x = {
  'x1':0,
  'x2':null,
  'x3':"xyz", 
  'x4': null,
   children: [
     { 'x1': 2, 'x3': 5},
     { 'x1': 3, 'x3': 6}
   ]
}

function replacer(key,value) { 
  if (value!==null) {
    if (fieldWhiteList.includes(key)) 
      return value;
  }
}
console.log(JSON.stringify(x, replacer,2));