問題描述在js中構造json的時候如何根據一個值來決定包不包含這個節點?問題出現的環境背景及自己嘗試過哪些方法當然可以用很多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 ;
}你期待的結果是什么?實際看到的錯誤信息又是什么?大神們有什么好的簡約的辦法么?
2 回答
紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
/**
*
* @param {Object} sources 傳入一個源數據Obj
* @param {Array} rule 傳入一個規則數組
* @param {Array} key 傳入需要判斷的key(sources的屬性)
* key要和rule對應
*/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)
當年話下
TA貢獻1890條經驗 獲得超9個贊
你這key值都不對應,估計沒對接好吧,只能自己映射了,不過為了優雅和減少代碼量,可以簡單封裝一下:
/**
* 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))- 2 回答
- 0 關注
- 807 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消
