简体   繁体   English

如果值为空,未定义或为空,如何从对象和/或数组中删除属性?

[英]How to remove a property from an object and/or array if the value is null, undefined or empty?

So I have a fairly complex object like this: 所以我有一个像这样的相当复杂的对象

var obj = {
    v1:"ok", 
    v2:[
        {av1:"foo",  av2:null}, // notice there's a null here
        {av1:"thing", av2:"stuff"}
    ], 
    v3: null, 
    v4:{
        ov1:"slim",
        ov2:"shady",
        ov3:null  // null
    }, 
    v5:[], // empty
    v6:{} // empty
}

I'd like to get this back: 我想把这个找回来:

var obj = {
    v1:"ok", 
    v2:[{av1:"foo"},{av1:"thing", av2:"stuff"}], 
    v4:{ov1:"slim",ov2:"shady"}
}

I'm trying to write a function that can delete anything that is null, undefined, or empty, but it's quickly becoming a spaghetti nightmare, and doesn't work. 我正在尝试编写一个函数,该函数可以删除任何为null,未定义或为空的内容,但它很快就成为了意大利面条梦night,并且无法正常工作。

I feel like there's a shorter more elegant way to do this, but this is my code so far: 我觉得有一种较短的更优雅的方法可以做到这一点,但这是到目前为止的代码

function deleteNulls(o){
    for(let i in o){
        if(typeof o[i] == "Object"){
            o[i] = deleteNulls(o[i])
        }
        else if(typeof o[i] == "Array"){
            o[i] = deleteNulls(o[i])
        }
        if(o[i] == null || o[i] == "undefined" || o[i] == [] | o[i] == {})
            delete o[i]
        else {
            if(typeof o == "Object"){
                delete this.o[i]
                return o
            }
            else if (typeof o == "Array")
                return o.filter(k => o[k] != null)
        }
    }
    return o
}

var obj = deleteNulls(obj)

I'm not interested in how to fix errors in the code above. 我对如何解决上面代码中的错误不感兴趣。 I could get this to work if I wanted to, 如果我愿意的话,我可以让它工作,

I'm wondering if there's an easier way. 我想知道是否有更简单的方法。

I'd suggest using something like lodash. 我建议使用类似lodash的东西。 It's tested and peer-reviewed for speed and efficiency. 经过速度测试和同行评审,以确保速度和效率。

Something like: 就像是:

var result = _.omitBy(my_object, _.isNil);

This would remove all null values, you'll need to change the second parameter to remove empty objects and arrays. 这将删除所有空值,您需要更改第二个参数以删除空对象和数组。

It helped me writing this solution to split the logic into a recursive clean function (simplifying existing object structures) and a shouldKeep function (which tells you whether a key can be removed entirely from an object structure based on its value). 它帮助我编写了此解决方案,以将逻辑分为递归clean函数(简化现有对象结构)和shouldKeep函数(该函数告诉您是否可以根据键值将键从对象结构中完全删除)。

Demo Snippet: 演示片段:

 var object = { v1: "ok", v2: [{ av1: "foo", av2: null }, // notice there's a null here { av1: "thing", av2: "stuff" } ], v3: null, v4: { ov1: "slim", ov2: "shady", ov3: null // null }, v5: [], // empty v6: {} // empty } function shouldKeep (o) { if (Array.isArray(o)) { return o.length } else if (typeof o === 'object') { return o && Object.keys(o).length } return o != null } function clean (o) { if (Array.isArray(o)) { o.forEach(clean) var a = o.filter(shouldKeep) o.length = a.length for (var i = 0; i < a.length; i++) { o[i] = a[i] } } else if (o && typeof o === 'object') { Object.keys(o).forEach(function (k) { clean(o[k]) if (!shouldKeep(o[k])) delete o[k] }) } return o } console.log(clean(object)) 
 .as-console-wrapper { min-height: 100vh; } 

Here is my take at it. 这是我的看法。 Should be good enough for most situations. 在大多数情况下应该足够好。

  var object = { v1: "ok", v2: [{ av1: "foo", av2: null }, // notice there's a null here { av1: "thing", av2: "stuff" } ], v3: null, v4: { ov1: "slim", ov2: "shady", ov3: null // null }, v5: [], // empty v6: {} // empty } function isEmpty(v) { return v == undefined || v == null || (Array.isArray(v) && v.length === 0) || (typeof v === 'object' && Object.keys(v).length === 0) } function removeFalsyFromObject(v) { var keys = Object.keys(v); keys.forEach(function(k){ var val = v[k]; if (isEmpty(val)) { delete v[k]; } else if (Array.isArray(val)) { removeFalsyFromArray(val); } else if (typeof val === 'object') { removeFalsyFromObject(val); } }) } function removeFalsyFromArray(a) { for (var i=0; i<a.length; i++) { var v = a[i]; if (isEmpty(v)) { a.splice(i,1); i--; } else if (Array.isArray(v)) { removeFalsyFromArray(v); } else if (typeof v === 'object') { removeFalsyFromObject(v); } } } function clean(obj) { removeFalsyFromObject(obj); return obj; } console.log(clean(object)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM