問題描述在js中構(gòu)造json的時(shí)候如何根據(jù)一個(gè)值來決定包不包含這個(gè)節(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í)際看到的錯(cuò)誤信息又是什么?大神們有什么好的簡約的辦法么?
2 回答

紅顏莎娜
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
/** * * @param {Object} sources 傳入一個(gè)源數(shù)據(jù)Obj * @param {Array} rule 傳入一個(gè)規(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)

當(dāng)年話下
TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
你這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))
添加回答
舉報(bào)
0/150
提交
取消