简体   繁体   English

根据对象的值从数组中删除和重新添加对象

[英]Removing and re adding objects from an array depending on their values

Using this array of objects as an example:以这个对象数组为例:

[ { "id": 1, "name": "John", "lastname": "Johnson", "registered": true }, { "id": 2, "name": "David", "lastname": "Davidson", "registered": false }, { "id": 3, "name": "Ben", "lastname": "Benson", "registered": false }, { "id": 4, "name": "Greg", "lastname": "Gregson", "registered": true }, { "id": 5, "name": "Peter", "lastname": "Peterson", "registered": true } ]

Then the array is mapped to be displayed然后将数组映射为显示

const displayedList = array.map(person => <Component key={person.id} /> )

Now if I just add a checkbox现在,如果我只添加一个复选框

<input onChange={onChangeHandler} type="checkbox" id="registered" name="registered" /> <label htmlFor="scales">Hide Registered</label>

Is there a way to go through the array and remove the items that have value of "registered" set as true if the checkbox is checked and put them back once it's unchecked again?有没有办法通过数组 go 并在选中复选框时删除“已注册”值设置为 true 的项目,并在再次取消选中后将它们放回原处? I've tried using the filter method and few others, but can't seem to figure out a way to do something like this.我已经尝试过使用过滤器方法和其他一些方法,但似乎无法找到一种方法来做这样的事情。 Any tips would be greatly appreciated任何提示将非常感谢

A filter over the array should work, but the condition may be a little tricky:数组上的filter应该可以工作,但条件可能有点棘手:

const hideRegistered = true; //For the simplicity of the example, this should be a state variable

...

const filteredUsers = users.filter((user) => hideRegistered ? !user.registered : true);

Then use filteredUsers to render your components.然后使用filteredUsers来渲染你的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM