JS 移除对象数组中,属性值全为空的项

const array = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Alice', age: null },
  { id: 3, name: 'Bob', age: undefined },
  { id: 4, name: 'Eve', age: '' },{ id: 5, name: '', age: '' }
];

const newArray = array.filter(obj => {
  const { id, ...rest } = obj; // 使用解构赋值将 id 属性排除
  const values = Object.values(rest);
  return values.some(value => value !== ''); // 使用 some() 方法检查是否存在非空白值
});

console.log(newArray);

 提取那些属性值全为空的项:

const array = [
  { id: 1, name: 'John', age: 25 },
  { id: 2, name: 'Alice', age: null },
  { id: 3, name: 'Bob', age: undefined },
  { id: 4, name: 'Eve', age: '' },{ id: 5, name: '', age: '' }
];

const newArray = array.filter(({ id, ...rest }) => {
  return Object.values(rest).every(value => value === '');
});

console.log(newArray);

 

posted on 2024-04-17 10:27  wakaka_wka  阅读(361)  评论(0编辑  收藏  举报