简体   繁体   中英

React copy items from one object to another, and see if object exists in current state

In React, I've got two state objects that hold multidimensional data like this:

this.state = {
    itemList: [
        {Id: 1, Name: "Bob", Age: 50},
        {Id: 2, Name: "Fred", Age: 26},
        {Id: 3, Name: "Joe", Age: 34},
    ],
    newItemList: [],
}

I want to call a function to add an item from the first list to the second list, using the item's Id. For example:

addItem(1);
addItem(2);
//NEW VALUES:
itemList: [
    {Id: 1, Name: "Bob", Age: 50},
    {Id: 2, Name: "Fred", Age: 26},
    {Id: 3, Name: "Joe", Age: 34},
],
newItemList: [
    {Id: 1, Name: "Bob", Age: 50},
    {Id: 2, Name: "Fred", Age: 26},
],

I then want to call a second function to search the second list, newItemList, to see if it contains an object by Id. If it does contain that Id, I want to remove the full object. Example:

checkItem(2);
function checkItem(item) {
    if(isInNewList(item)) {
        //Function checks for item 2 and removes item 2 from list
    }
}
//NEW VALUE:
newItemList: [
    {Id: 1, Name: "Bob", Age: 50},
],

I've done quite a bit of reading, but can't seem to grasp the concepts to make both of these happen easily. Both itemList and newItemList are stored in the current component's state. Thanks for any help!!

Use findIndex to check if the array contains the element, If it contains the element then use filter function to create a new array which does not include the object with the required id

 let itemList = [{ Id: 1, Name: "Bob", Age: 50 }, { Id: 2, Name: "Fred", Age: 26 }, { Id: 3, Name: "Joe", Age: 34 }, ] let newItemList = [{ Id: 1, Name: "Bob", Age: 50 }, { Id: 2, Name: "Fred", Age: 26 }, ] function searchByIndex(id) { let getIndex = newItemList.findIndex(item => id === item.Id); if (getIndex !== -1) { newItemList = newItemList.filter(item => item.Id !== id) } } searchByIndex(2); console.log(newItemList) 

I think a quite clean solution would be to do these operations with item IDs only

const itemIds = [
        {Id: 1, Name: "Bob", Age: 50},
        {Id: 2, Name: "Fred", Age: 26},
        {Id: 3, Name: "Joe", Age: 34},
    ].map(item => item.id)

this.state = {
    itemIds,
    newItemIds: [],
}

const addItem = id => this.setState(
  state => ({ newItemIds: state.newItemIds.concat(id) })
)

const removeIfPresent = idToRemove => this.setState({ 
   state => ({ newItemsIds: state.newItems.filter(id => id !== idToRemove) })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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