JS去除对象数组中指定字段为空的数据
可以使用 filter() 方法结合 some() 方法来过滤掉对象数组中指定字段为空的对象。
filter() 方法可以筛选符合条件的元素,而 some() 方法可以检查当前元素的指定字段是否为空。
例:
const arr = [
{ id: 1, name: 'foo', age: 20 },
{ id: 2, name: 'bar', age: null },
{ id: 3, name: 'baz', age: undefined },
{ id: 4, name: 'qux' },
];
现在想要去除上面对象数据中所有 age 字段为空(即值为 null 或 undefined)的元素,可以这样写:
const filteredArr = arr.filter((obj) => {
return !(Object.prototype.hasOwnProperty.call(obj, 'age') && (obj.age === null || obj.age === undefined));
});
console.log(filteredArr); // [{ id: 1, name: 'foo', age: 20 }]
首先使用 Object.prototype.hasOwnProperty.call() 方法来检查每个元素是否具有 age 字段。
然后使用条件运算符 && 来检查 age 的值是否为空。
最后在前面加上了一个取反运算符 !,将符合条件的元素过滤掉。
filter() 方法会返回一个新数组,其中包含未被过滤的元素。
同理,如果我们要去掉对象数组中的,age 不为空的对象,可以这样写:
const filteredArr = arr.filter((obj) => {
return Object.prototype.hasOwnProperty.call(obj, 'age') && (obj.age === null || obj.age === undefined);
});
console.log(filteredArr); // [{id: 2, name: 'bar', age: null}, {id: 3, name: 'baz', age: undefined}, {id: 4, name: 'qux'}]