Constructing json problem in js

problem description

how do you decide whether to include this node based on a value when constructing a json in js?

the environmental background of the problems and what methods you have tried

of course you can do it with a lot of if, such as

            let req = {};
            if(this.timeSelect.start != ""){
                req.startTs = this.timeSelect.start;
            }
            if(this.timeSelect.end != ""){
                req.endTs = this.timeSelect.end;
            }
            if(this.userId != ""){
                req.userId = this.userId;
            }
            if(this.auditType != "1"){
                req.checkType = this.auditType;
            }
            if(this.opter != ""){
                req.operator = this.opter;
            }
            if(this.auditStatus != "0"){
                req.result = this.auditStatus ;
            }

what result do you expect? What is the error message actually seen?

do the gods have any good and simple ways?

Apr.25,2021

/**
 * 
 * @param {Object} sources Obj
 * @param {Array} rule  
 * @param {Array} key keysources
 * keyrule
 */
function assigment(sources, rule, key){
    var target = {}
    for(let i = 0; i < key.length; i PP){
        if(rule[i]){
            target[key[i]] = sources[key[i]]
        }
    }
    return target
}
var sources = {a: 1, b: '', c: '0'}
var rule = [
    sources.a != '',
    sources.b != '',
    sources.c != '0',
]
var key = ['a', 'b', 'c'];
var target = assigment(sources, rule, key)

console.log(target)

your key values do not correspond to each other. It is estimated that you have no good connection, so you can only map it yourself. However, in order to be elegant and reduce the amount of code, you can simply encapsulate it:

    /**
    * k: reqkey
    * p:  key
    * c: 
    * v: 
    **/
    function setVal({ k, p, c, v = '' }) {
      const _v = c[p]
      if (_v != v) req[k] = _v
    }
    var arr = [
      { k: startTs, p: start, c: this.timeSelect },
      { k: endTs, p: end, c: this.timeSelect },
      { k: userId, p: userId, c: this },
      { k: checkType, p: auditType, c: this, v: '1' }
    ]
    arr.forEach(item => setVal(item))

The function default value + structure of

es6 can solve this problem
A simple example

function test({a = 'default'}){
  console.log(a)
}
test({b: 'b'})
// default
test({a: 'a'})
// a

but if you need to judge a lot of things, the function parameters will be more difficult to write

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b371d4-2c075.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b371d4-2c075.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?