1

image.png

有没有简单的方法检测对象中为-1的都转空呢?

最好是循环自动修改

林小木 143
12月4日提问
4 个回答
0

已采纳
var obj = {
        a:0,
        b:2,
        c:4,
        d:-1,
        e:5,
        f:9,
        g:-1,
        h:0
    }
    var newObj = obj;
    for(i in obj){
        if(obj[i]==-1){
            newObj[i] = 1
        }
    }
    console.log(newObj)
0

jashjdasjsahdjahsgdhjasdhajkshd

0
let obj = {
    a:1,
    b:-1,
    c:2,
    d:-1
}
let newObj = {};
Object.entries(obj).forEach(item => {
    newObj[item[0]] = item[1] === -1?'':item[1];
})
console.log(newObj);
0

说了多少遍 immutable,immutable(熊猫打人),要考的呀:

const newObj = Object.fromEntries(
    Object.entries(obj).filter(([_, val]) => val !== -1)
)

const newObj = Object.entries(obj)
    .filter(([_, val]) => val !== -1)
    .reduce((pre, [key, val]) => {
        pre[key] = val
        return pre
    }, {})

撰写答案

推广链接