在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ 在js中構(gòu)造json問題

在js中構(gòu)造json問題

問題描述

在js中構(gòu)造json的時候如何根據(jù)一個值來決定包不包含這個節(jié)點(diǎn)?

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

當(dāng)然可以用很多if來搞,比如

            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 ;
            }

你期待的結(jié)果是什么?實(shí)際看到的錯誤信息又是什么?

大神們有什么好的簡約的辦法么?

回答
編輯回答
懶豬

es6 的函數(shù)默認(rèn)值 + 結(jié)構(gòu)可以解決這個問題
簡單的例子

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

但是如果需要判斷很多內(nèi)容的話,函數(shù)參數(shù)會比較難寫

2017年8月5日 08:08
編輯回答
萢萢糖

你這key值都不對應(yīng),估計(jì)沒對接好吧,只能自己映射了,不過為了優(yōu)雅和減少代碼量,可以簡單封裝一下:

    /**
    * k: req要掛載的key
    * 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))
2017年7月4日 02:56
編輯回答
尐懶貓
/**
 * 
 * @param {Object} sources 傳入一個源數(shù)據(jù)Obj
 * @param {Array} rule 傳入一個規(guī)則數(shù)組 
 * @param {Array} key 傳入需要判斷的key(sources的屬性)
 * key要和rule對應(yīng)
 */
function assigment(sources, rule, key){
    var target = {}
    for(let i = 0; i < key.length; i ++){
        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)
2017年1月18日 12:59