根据值数组中的值删除对象数组中的对象 - Javascript

时间:2018-04-19 20:49:09

标签: javascript redux reducers

我正在尝试在redux中添加一个reducer,它根据值数组删除状态中的多个项目。

说我有阵列

const idArray = ["935", "933", "930"];

我想删除id属性与idArray中的一个值匹配的对象,并返回一个包含其余值的新数组。

const objectsArray= [
  { 
    name: "Kevin", 
    color: "red", 
    id: "935"
  },
  { 
    name: "Ana", 
    color: "white", 
    id: "815"
  },
  { 
    name: "Maria", 
    color: "silver", 
    id: "035"
  },
  { 
    name: "Victor", 
    color: "red", 
    id: "935"
  },
  { 
    name: "Vanessa", 
    color: "red", 
    id: "933"
  },
]

所以在这种情况下,我想删除名称为KevinVanessaVictor的对象,并返回一个带Ana的新数组, Maria

这是我到目前为止在我的减速机中所拥有的:

case PeopleActions.DELETE_PEOPLE:
  if (action.id.length === 1) {
    return state.filter(people =>
      people.id !== action.id[0]
    );
  } else {
    const deletePeople: any = () => {
      for (let i = 0; i < action.id.length; i++) {
        return state.filter(poeple =>
          people.id !== action.id[i]
        );
      }
    };
    return deletePeople;
  }

1 个答案:

答案 0 :(得分:1)

我认为objectsArray被标记为const,然后重新分配新数组,这意味着没有filter()

如果你需要在适当的位置改变数组,最好的选择可能是简单地向后循环数组并随时拼接:

&#13;
&#13;
const idArray = ["935", "933", "930"];

const objectsArray= [{   name: "Kevin",   color: "red",   id: "935"},{   name: "Ana",   color: "white",   id: "815"},{   name: "Maria",   color: "silver",   id: "035"},{   name: "Victor",   color: "red",   id: "935"},{   name: "Vanessa",   color: "red",   id: "933"},]

for (let i = objectsArray.length-1; i >=0 ; i--){
    if(idArray.includes(objectsArray[i].id)){
        objectsArray.splice(i,1);
        }
}

console.log(objectsArray);
&#13;
&#13;
&#13;