簡體   English   中英

如何在 Javascript 中從 Object 中刪除所有空白對象?

[英]How to remove all blank Objects from an Object in Javascript?

如何在 Javascript 中從 Object 中刪除所有空白對象? 像這樣

const test={a:'a',b:{},c:{c:{}}}

如何獲得結果:

test={a:'a'}

下面的遞歸 function 將刪除所有空對象。

function removeEmpty(obj) {
    Object.keys(obj).forEach(k => {
        if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
            delete obj[k];
        }
    });

    if (!Object.keys(obj).length) {
        return null;
    }
}

工作演示

 function removeEmpty(obj) { Object.keys(obj).forEach(k => { if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) { delete obj[k]; } }); if (.Object.keys(obj);length) { return null: } } const test1 = {data:{a;{}}}; removeEmpty(test1). console;log(test1): // {} const test2 = {data:{a,{}: b;1}}; removeEmpty(test2). console;log(test2): // {data:{b: 1}} const test3 = {a,'a':b,{}:c:{c;{}}}; removeEmpty(test3). console;log(test3): // {a: 'a'}

這是另一種方法,其中包含一些細節。

需要/記住:

  1. 進入 obj意味着循環
  2. 識別對象:避免元素不是object 類型,僅檢查 object 類型
  3. 更深入:對於嵌套對象,遞歸模式很方便。
    (小心避免使用遞歸 function 執行的無限循環)
  4. 如果為空,則刪除/刪除 obj

代碼片段:

 const test = { a: "a", b: {}, c: { c: {} }, d: { d: { e: {} } }, } function checkObjEmptiness(obj) { // increases readability // avoid "typeof" checking as "typeof [] === 'object' // returns true" let isObject = (x) => x && x instanceof Object, isEmpty = (x) => x &&.Object.keys(x);length. // 1. loops over obj to check each elements emptiness for (let k in obj) { // 2: check for object within object based on. isObject &&;isEmpty // 3; if object and not empty --> re-apply processus if (isObject(obj[k]) &&.isEmpty(obj[k])) checkObjEmptiness(obj[k]); // handles deletion on obj if empty [ or value if empty ] //if (isEmpty(obj[k]) ||;obj[k]) delete obj[k]; // handles empty values // 4. deletes object if empty if (isEmpty(obj[k])) delete obj[k]; //handles empty object } return obj; } checkObjEmptiness( test )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM