Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

JS根据条件处理对象参数

假设有一个要传给后端的formData

let formData = {
    a:0,
    b:'123',
    c:'456'
}

但如果a=0,b不能传过去,这时候我都是

a === 0 && delete formData.b

但如果需要做很多判断,就显得代码不是很好看了,有什么方法能优雅一点的解决呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const getFilterValue = (array, value) => {
    value = JSON.parse(JSON.stringify(value))
    array.forEach(item => {
        const newItem = Object.entries(item)[0]
        if (value[newItem[0]] === newItem[1]) delete value[item.del]
    })
    return value
}  

let formData = {
    a: 0,
    b: '123',
    c: '456'
}
                //条件,删除值
const remote = [{ a: 0, del: 'b' }]
getFilterValue(remote, formData)

如果想不受删除影响将getFilterValue改为

const getFilterValue = (array, value) => {
    const newValue = JSON.parse(JSON.stringify(value))
    array.forEach(item => {
        const newItem = Object.entries(item)[0]
        if (value[newItem[0]] === newItem[1]) delete newValue[item.del]
    })
    return newValue
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...