如何从数组中删除一些对象

时间:2020-07-24 06:33:24

标签: javascript

我正在尝试从数组中删除一个或几个对象。符合条件已完成=== true 。数组可以动态包含更多或更少的对象。

const array = [{
    completed: false,
    id: 1595572089666,
    title: "1"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "2"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "3"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "4"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "5"
  }
];

function removeCompleted(arr) {
  arr.reduce(item => {
    return item.completed === true ? item.splice(1, 1) : false;
  });
}

1 个答案:

答案 0 :(得分:2)

您可以使用filter方法基于completed属性删除对象。

let array = [{
    completed: false,
    id: 1595572089666,
    title: "1"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "2"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "3"
  },
  {
    completed: true,
    id: 1595572089666,
    title: "4"
  },
  {
    completed: false,
    id: 1595572089666,
    title: "5"
  }
];

array = array.filter(item => item.completed != true);

console.log(array);