简体   繁体   English

如何按条件删除对象中的对象

[英]How to delete object in object by criteria

I have this: 我有这个:

Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object, 13: Object, 14: Object, 15: Object}1: Object2: Object3: Object1: Object2: Object3: Object4: Object5: Object__proto__: Object4: Object1: Object2: ObjectfromLevel: "1"toLevel: "6"__proto__: Object3: Object4: Object5: ObjectfromLevel: "1"toLevel: "6"__proto__: Object__proto__: Object5: Object6: Object1: Object2: Object3: ObjectfromLevel: "1"toLevel: "6"__proto__: Object4: Object5: Object__proto__: Object7: Object8: Object9: Object10: Object11: Object12: Object1: Object2: ObjectfromLevel: undefinedtoLevel: undefined__proto__: Object3: Object4: Object5: Object__proto__: Object13: Object14: Object15: Object1: Object2: Object3: Object4: ObjectfromLevel: undefinedtoLevel: undefined__proto__: Object5: Object6: Object7: Object8: Object9: Object10: Object11: Object12: Object13: Object14: Object15: Object16: Object17: Object18: Object__proto__: Object__proto__: Object

I need to remove each object that has undefined properties. 我需要删除每个具有未定义属性的对象。 And if there isn't any child objects in the parent object, then i need to delete this parent object. 如果父对象中没有任何子对象,那么我需要删除此父对象。 In other words i need to have only objects that has properties not equals to undefined. 换句话说,我只需要具有不等于未定义属性的对象。

Working JSFiddle: https://jsfiddle.net/LeoAref/qmnz6w61/ 工作的JSFiddle: https ://jsfiddle.net/LeoAref/qmnz6w61/

var topObject = {
    x: {},
    y: undefined,
    z: {
        n: 11,
        c: undefined,
        o: {
            a: undefined,
            l: 44
        }
    }
};

function checkObject (obj) {
    // Loop through obj key and check them
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            // Key value equals undefined, then delete it.
            if(obj[key] === undefined) {
                delete obj[key];
            } 

            // Check this child if it is an object
            else if(obj[key].constructor === Object) {
                checkObject(obj[key]);
            }
        }
    }
}

If you want to delete the empty objects as well, use this check: 如果还要删除空对象,请使用此检查:

JSON.stringify(obj[key]) === '{}' // true if obj[key] is empty object

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

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