从 JavaScript 中的数组中删除空对象
从数组中删除空对象:
-
使用
Array.filter()
方法遍历数组。 -
将每个对象传递给
Object.keys()
方法并检查键的长度是否不等于 0。 -
filter
方法将返回一个不包含空对象的新数组。
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);
我们传递给 Array.filter
方法的函数被数组中的每个元素(对象)调用。
如果函数返回真值,则 filter
方法将该元素添加到结果数组。
Object.keys
方法返回一个包含对象键的数组。
console.log(Object.keys({})); // 👉️ []
console.log(Object.keys({id: 1})); // 👉️ ['id']
如果对象没有键值对,则该方法返回一个空数组。
如果它至少有 1 个键值对,我们只返回 true 并将对象添加到结果数组。
请注意
,如果使用空数组[]
或数字 0 调用Object.keys(obj).length
方法将返回 0。
console.log(Object.keys(0).length); // 👉️ 0
console.log(Object.keys([]).length); // 👉️ 0
如果我们的数组包含对象以外的类型,请使用以下方法仅从数组中删除空对象。
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);
我们使用 &&
(与)运算符来指定必须满足所有条件才能运行 if 块。
我们首先检查元素是否有对象类型,但这还不够,因为 JavaScript 数组也有对象类型。
console.log(typeof []) // 👉️ 'object'
然后我们检查元素不是数组并且对象是空的。
如果满足所有这些条件,我们就知道我们有一个空对象,不应将其添加到结果数组中,因此我们返回 false。
在所有其他情况下,数组元素不是空对象并被添加到新数组中。
大多数情况下,在数组中存储多种不同类型是一种反模式。 如果我们需要在同一个数组中存储不同的类型,很可能是做错了什么。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。