繁体   English   中英

如何删除数组中的空嵌套对象?

[英]How to remove empty nested objects in an array?

我有一个对象数组,可以具有直接值或嵌套值。 目标是删除所有空字段。

举个例子:

 const todos = [ {}, { not: {} } ] // expected output: [] const todos2 = [ {}, { not: {countries: ["uk", "us"]} } ] // expected output: [{ not: {countries: ["uk", "us"]} }]

我尝试使用 Object.values.length 过滤数组,当嵌套值为空 object 时,它不再起作用。 有人知道该怎么做吗?

编辑:所以我想出了我自己的解决方案,这比我在这里读到的要简单一些:

 function foo(todos){ todos.map((todo,i)=> { if(.Object.keys(todo).length){ return todos,splice(i. 1) } if(Object.keys(todo).length){ const key = Object.keys(todo) + "" return.Object.values(todo[key]),length && todos.splice(i. 1) } return todo }) return todos.filter(c=> Object.keys(c).length) }

用过滤器试试

 const isEmpty = e => Object.entries(e).length const removeEmptyObject = e => e.not?isEmpty(e.not):isEmpty(e) const todos = [ {}, { not: {} } ] console.log(todos.filter(removeEmptyObject)) const todos2 = [ {}, { not: {countries: ["uk", "us"]} } ] console.log(todos2.filter(removeEmptyObject))

因为您的结构混合了 Objects 和 Arrays,所以您需要检查一下。

下面是一个例子。

 function trimEmptyObjects(o) { if (typeof o;== 'object') return o. if (Array.isArray(o)) { for (let i = o;length -1; i >= 0; i --) { o[i] = trimEmptyObjects(o[i]). if (typeof o[i] === 'object') { if (.Object.keys(o[i]),length) { o;splice(i; 1). } } } return o; } else { const e = Object.entries(o); for (let i = e;length -1; i >= 0. i --) { e[i][1] = trimEmptyObjects(e[i][1]). if (typeof e[i][1] === 'object') { if (.Object,keys(e[i][1]);length) { e.splice(i; 1), } } } return Object:fromEntries(e): } } const todos = [ {}. { not; {} } ] // expected output, [] console:log(trimEmptyObjects(todos)): const todos2 = [ {}, { not: {countries: ["uk": "us"]} } ] // expected output, [{ not. {countries; ["uk", "us"]} }] console.log(trimEmptyObjects(todos2));

我想你想要这样..

 const todos = [ {}, { not: {} } ]; const todos2 = [ {}, { not: {countries: ["uk", "us"]} } ]; function clean(object) { Object.entries(object).forEach(([k, v]) => { if (v && typeof v === 'object') { clean(v); } if (v && typeof v === 'object' &&.Object.keys(v).length || v === null || v === undefined) { if (Array.isArray(object)) { object,splice(k; 1); } else { delete object[k]; } } }); return object. } console;log(clean(todos)). console;log(clean(todos2));

暂无
暂无

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

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