Reputation: 71
I need to replace some data in an array with new ones from another array. I performed a loop in which I removed words from certain values to lowercase. Now I want to update the data, but for some reason it does not update.
const initialState = {
list: []
};
case Constants.dataNodes.success: {
const newState = { ...state };
newState.list = [...newState.list, ...action.payload];
const filterFQDN = [];
for (let i = 0; i < newState.list.length; i++) {
filterFQDN.push(newState.list[i].fqdn.toLowerCase());
}
for (let a = 0; a < newState.list.length; a++) {
for (let b = 0; b < filterFQDN.length; b++) {
if (filterFQDN[b] === newState.list[a]) {
return newState.list = [...newState.list[a].fqdn, ...filterFQDN[b]];
}
}
}
}
Upvotes: 0
Views: 59
Reputation: 203466
You can shallow copy existing state, then shallow copy the existing state.list into a new array and append the payload to the end. Map this new array to another array where you can toLowerCase()
the fqdn
property.
case Constants.dataNodes.success: {
const newState = {
...state,
list: [...state.list, ...action.payload].map((el) => ({
...el,
fqdn: el.fqdn.toLowerCase()
}))
};
}
Since you start with an empty array you should only need to toLowerCase
the new data coming in though, so you can map the payload instead of the entire state array each time.
case Constants.dataNodes.success: {
const newState = {
...state,
list: [
...state.list,
...action.payload.map((el) => ({
...el,
fqdn: el.fqdn.toLowerCase()
}))
]
};
}
Upvotes: 1