I am trying to assign clone/merge object, that has array where id matches or add to an end:
newState = Object.assign({}, state, {
data: {
newest: {
result: action.payload.result,
list: action.payload.items,
request: action.payload.items
},
itemList: [
...state.data.itemList,
{
id: action.payload.id,
list: action.payload.items,
request: action.payload.items
}
]
}
});
In this case ...state.data.itemList
is an array with objects where I want to find an existing object with ID
and merge list + request nested objects. However, if there is no object with that ID
I want to add it to the list.
Current approach always adds it to the end, which of course is not what I want.
Thanks.
Don't feel pressured into making the new state in one operation. Here would be my implementation. I would check my array for the current id using Array#some
. Here are some fun ES6 tricks too.
const newState = {...state}
const {result, items, id, items} = action.payload
const data = {newest: {result, list: items, request: items}}
const hasId = newState.data.itemList.some(item => item.id === id)
if (!hasId) {
newState.data.itemList.push({id, list: items, request: items})
}
return {...newState, data}
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.