ES6遍历对象的值不为空
时间: 2023-08-12 19:33:17 浏览: 137
你可以通过使用`Object.values()`方法和`Array.prototype.filter()`方法来遍历对象的值并过滤掉为空的值。具体实现如下:
```javascript
const obj = {
a: 1,
b: null,
c: undefined,
d: '',
e: false,
f: 0,
g: 'hello'
};
const nonEmptyValues = Object.values(obj).filter(value => {
return value !== null && value !== undefined && value !== '' && value !== false && value !== 0;
});
console.log(nonEmptyValues); // [1, 'hello']
```
这段代码会输出对象`obj`中所有不为空的值,即`1`和`'hello'`。
相关问题
用ES6遍历对象的值判断是否为空
你可以使用`Object.values()`方法和`Array.prototype.every()`方法来遍历对象的值并判断是否为空。具体实现如下:
```javascript
const obj = {
a: 1,
b: null,
c: undefined,
d: '',
e: false,
f: 0,
g: 'hello'
};
const isAllValuesNonEmpty = Object.values(obj).every(value => {
return value !== null && value !== undefined && value !== '' && value !== false && value !== 0;
});
console.log(isAllValuesNonEmpty); // false
```
这段代码会判断对象`obj`中所有值是否都不为空,即返回`false`。如果你想判断是否存在至少一个不为空的值,可以使用`Array.prototype.some()`方法,具体实现类似。
ES6写法两次循环遍历一个二维数组,去校验最里面的对象值是否为空
ES6中可以使用数组的 `forEach` 方法来代替循环语句,简化代码。示例代码如下:
```javascript
const arr = [
[{name: 'Alice', age: 22}, {name: 'Bob', age: 30}],
[{name: 'Charlie', age: 25}, {name: 'David', age: 28}],
[{name: '', age: null}, {name: 'Eva', age: 24}]
];
arr.forEach((row, i) => {
row.forEach((obj, j) => {
if (!obj.name || !obj.age) {
console.log(`第 ${i} 行,第 ${j} 列的对象值为空`);
}
});
});
```
在这个例子中,我们使用了数组的 `forEach` 方法来对二维数组进行遍历。在外层的 `forEach` 中,第一个参数 `row` 表示当前行的数组,第二个参数 `i` 表示当前行的索引。在内层的 `forEach` 中,第一个参数 `obj` 表示当前对象,第二个参数 `j` 表示当前对象的索引。这样就可以对二维数组中的所有对象进行校验了。
需要注意的是,这里的判断条件和上面的示例一样,即只要 `name` 或 `age` 中有一个为空,就会被判断为空值。如果需要更加精确的判断,可以根据具体情况进行修改。
阅读全文
相关推荐
















