从 JavaScript 中的数组中删除空对象 {} []
  ri1zGgYuFMgV 2023年12月05日 15 0


只有对象的情况下,

const arr = [{}, {id: 1}, {}, {id: 2}, {}];

const results = arr.filter(element => {
  if (Object.keys(element).length !== 0) {
    return true;
  }

  return false;
});

// 👇️ [{id: 1}, {id: 2}]
console.log(results);

数据类型多样的情况下,

const arr = [{}, {id: 1}, 'a', 0, {}, []];

const results = arr.filter(element => {
  if (
    typeof element === 'object' &&
    !Array.isArray(element) &&
    Object.keys(element).length === 0
  ) {
    return false;
  } else {
    return true;
  }
});

// 👇️ [{id: 1}, 'a', 0, []]
console.log(results);

再来一个例子:

test = [
          {},
          {},
          {},
          {},
          {},
          {
            "value": 3000,
            "category": 6,
            "id": "7",
            "label": "A8",
            "name": "A8"
          },
          {}
        ]
        

const results = test.filter(element => {
  if (
    typeof element === 'object' &&
    !Array.isArray(element) &&
    Object.keys(element).length === 0
  ) {
    return false;
  } else {
    return true;
  }
});

console.log(results);

判断是否有{}

// 对数组进行过滤
let myArray = ["apple", {}, "orange", "grape"];

// 判断是否存在‘{}’或‘[]’! 若存在空,返回true,否则,返回false
function iskong(obj) {
	// 把obj转为JSON字符串
	let toStr = JSON.stringify(obj);
	// 通过indexOf查找字符串是否存在‘{}’或‘[]’
	return toStr.indexOf('{}') !== -1 || toStr.indexOf('[]') !== -1;
}


console.log(iskong(myArray))

一个实例

let arr0 = [
  {
    "name": "Alzheimer",
    "value": 0,
    "category": 19,
    "id": "1",
    "children": [
      {
        "children": [
          {},
          {},
          {},
          {},
          {},
          {},
          {}
        ]
      },
      {
        "children": [
          {},
          {},
          {},
          {}
        ]
      }
    ]
  }
];


let arr1 = [
  {
    "name": "Alzheimer",
    "value": 0,
    "category": 19,
    "id": "1",
    "children": [
      {
        "value": 3000,
        "category": 6,
        "children": [
          {},
          {},
          {},
          {},
          {},
          {
            "value": 3000,
            "category": 6,
            "id": "7",
            "label": "ACSL8",
            "name": "ACSL8"
          },
          {}
        ],
        "id": "type_6",
        "label": "Protein",
        "name": "Protein"
      },
      {
        "children": [
          {},
          {},
          {},
          {}
        ]
      }
    ]
  }
];


let arr2 = [
  {
    "name": "Alzheimer",
    "value": 0,
    "category": 19,
    "id": "1",
    "children": [
      {
        "value": 3000,
        "category": 6,
        "children": [
          {
            "value": 3000,
            "category": 6,
            "id": "2",
            "label": "EIF4ENIF1",
            "name": "EIF4ENIF1"
          },
          {},
          {
            "value": 3000,
            "category": 6,
            "id": "4",
            "label": "ACSL5",
            "name": "ACSL5"
          },
          {},
          {
            "value": 3000,
            "category": 6,
            "id": "6",
            "label": "ACSL7",
            "name": "ACSL7"
          },
          {},
          {
            "value": 3000,
            "category": 6,
            "id": "8",
            "label": "ACSL9",
            "name": "ACSL9"
          }
        ],
        "id": "type_6",
        "label": "Protein",
        "name": "Protein"
      },
      {
        "value": 3000,
        "category": 19,
        "children": [
          {
            "value": 3000,
            "category": 19,
            "id": "9",
            "label": "pterygium1",
            "name": "pterygium1"
          },
          {
            "value": 3000,
            "category": 19,
            "id": "10",
            "label": "pterygium2",
            "name": "pterygium2"
          },
          {
            "value": 3000,
            "category": 19,
            "id": "11",
            "label": "pterygium3",
            "name": "pterygium3"
          },
          {
            "value": 3000,
            "category": 19,
            "id": "12",
            "label": "pterygium4",
            "name": "pterygium4"
          }
        ],
        "id": "type_19",
        "label": "Disease",
        "name": "Disease"
      }
    ]
  }
];





// 数据后处理步骤

dealdata = arr2

// 1、删除数据中的children[]的空{}

function removeEmptydict (node) {
  
  
  node.forEach(item => {
   
    if ('children' in item && item.children.length) {
       
        item.children = item.children.filter(element => {
              if (
                typeof element === 'object' &&
                !Array.isArray(element) &&
                Object.keys(element).length === 0
              ) {
                return false;
              } else {
                return true;
              }
            });
            
        removeEmptydict(item.children)
    }
    
  })
  
}

removeEmptydict (dealdata)  //调用1

console.log("删除空{}:", JSON.stringify(dealdata, null, 2))





// 2、判断children此时此刻是否为[]
// 删除空children []
function removeEmptyChildren (node) {
  node.forEach(item => {
 
    
    if ('children' in item && item.children.length === 0) {
      delete item.children
     
    } 
    
    else if ('children' in item && item.children.length) {
      removeEmptyChildren(item.children)
    }
    
  })
  
}

removeEmptyChildren (dealdata) //调用2

console.log("删除空children[]:", JSON.stringify(dealdata, null, 2))



removeEmptydict (dealdata)  //调用3

console.log("再删除空children[]:", JSON.stringify(dealdata, null, 2))


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月05日 0

暂无评论

推荐阅读
ri1zGgYuFMgV