score:3
there are 3 problems in your code:
- you are setting the value of
key
to an object while theitems
is expected to have an array to ids.
// current
[key]: {
...prevstate[key],
[x.id]: undefined
}
// expected
[key]: prevstate[key].filter(item => item.id === matchingid)
- if you intend to remove an object from an array based on some condition, you should be using
filter
as pointed out in owen's answer because what you are doing is something else:
const a = { xyz: 123, xyz: undefined };
console.log(a); // { xyz: undefined} - it did not remove the key
to make your code more readable, it is expected to manipulate the entire object
items
and then, set it to the state once usingsetitems
- in contrast to callingsetitems
multiple times inside a loop and based on some condition.this makes your code more predictable and leads to fewer re-renders.
also, the solution to your problem:
// define this somewhere
const initial_state = {
"some_id1": [
{
"id": 93979
},
{
"id": 93978
}
],
"some_id2": [
{
"id": 93961
},
{
"id": 93960
}
]
};
// state initialization
const [items, setitems] = react.usestate(initial_state);
// handler to remove the nested object with matching `id`
const removebynestedid = (id, items) => {
const keys = object.keys(items);
const updateditems = keys.reduce((result, key) => {
const values = items[key];
// since, we want to remove the object with matching id, we filter out the ones for which the id did not match. this way, the new values will not include the object with id as `id` argument passed.
result[key] = values.filter(nesteditem => nesteditem.id !== id)
return result;
}, {});
setitems(updateditems);
}
// usage
removebynestedid(93961, items);
score:0
your way solution
for (const key in items) {
if (object.hasownproperty.call(items, key)) {
const element = items[key];
element.foreach(x => {
if (x.id === singleitem.id) {
setitems(prevstate => ({
...prevstate,
//filter will remove the x item
[key]: element.filter(i => i.id !== x.id),
}))
}
})
}
}
short solution.
for(const k in items) items[k] = items[k].filter(x => x.id !== singleitemid);
const items = {
"some_id1": [
{
"id": 93979,
},
{
"id": 93978,
}
],
"some_id2": [
{
"id": 93961,
},
{
"id": 93960,
}
]
}
const singleitemid = 93979;
for (const k in items) items[k] = items[k].filter(x => x.id !== singleitemid);
console.log(items);
//setitems(items)
score:0
you could try using the functional update.
const [data, setdata] = [{id:1},{id:2},{id:3}...]
once you know the id which you need to remove.
setdata(d=>d.filter(item=>item.id !== id));
score:1
probably a simple reduce
function would work, loop over the entries and return back an object
const data = {"some_id1": [{"id": 93979},{"id": 93978}],"some_id2": [{"id": 93961},{"id": 93960}]}
const remove = ({id, data}) => {
return object.entries(data).reduce((prev, [nextkey, nextvalue]) => {
return {...prev, [nextkey]: nextvalue.filter(({id: itemid}) => id !== itemid)}
}, {})
}
console.log(remove({id: 93961, data}))
Source: stackoverflow.com
Related Query
- updating object inside array inside object using prevState and the useState hook
- useState hook can only set one object at the time and return the other object of the same array to initial state
- update the array of object using useState hook
- how do i update state in react for updating the value of an object inside an array using array.map function
- Updating and merging state object using React useState() hook
- Updating the array object in React state using immutability helper
- Do I need to use the spread operator when using useState hook on object when updating?
- Adding a key-value pair to an object inside loop using React useState hook
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- Get object array from axios and using return value call another axios function and append the output to first result
- How to manage the asynchrounous nature of useState hook when setting a value and using it directly after
- updating a useState to the value that it's already holding inside of a custom React hook causes infinite re-render
- How to check if the array of object is null using react and javascript?
- Updating just part of state and keeping others same when using useState hook
- How to find the count of some object property in array of objects using react and javascript?
- How to define TypeScript types when used with React useState and the previous state inside a state updating function?
- React hook using useEffect with an array inside the dependencies array
- My useState hook is not updating itself and when i am trying to get data using filter, its not working
- How can I get all the object inside an object which is present inside an array and add the result into another array
- How to count object property occurrence in an array by adding count property to the object properties and updating each occurrence of count?
- Why the state is still showing Promise while using redux? and how should I access the array inside the result?
- useState set method inside useEffect hook not updating till refreching the page
- react-native textInput inside flatlist using array of object with useState, always rerender when type something the keyboard goes down
- modify and insert new object in array of objects with useState hook
- React - Updating previous array with new values using useState hook
- Append a item to an array that is inside a object with useState Hook
- Updating an object inside array using this.setState
- How do I increment the count of a selected index of state object using setState method given by useState hook in my react application
- how to add and remove number without duplicate in the state object inside the array in Reactjs?
- Change the value of all the fields in an object using useState hook
More Query from same tag
- Mailgun Attachment + Axios
- Import a function from JS to JSX
- Between NativeBase and Shoutem, which is best to use for React Native?
- WebSocket connection to "wss" sockjs-node failed for CRA and nginx reverse proxy
- How do you update your project to use the latest version of javascript?
- react-bootstrap-table-next on selectRow selects all Rows
- babel-loader syntax error only for imported modules
- How to change the state with React TypeScript 2.0?
- React Material-UI how to save TextFields in Typescript
- TypeError: arr.slice is not a function or its return value is not iterable
- Cannot test redirecting in react router with enzyme
- React js navigator implemented in web app
- React-Router not receiving props if it's the same path, but different param?
- In React, what is the difference between setState and forceUpdate
- get input value in react failed?
- How can i move a text right of the screen and back to left of screen
- how to use imask react dynamic mask?
- How to pass props to Screen component with a tab navigator?
- Have problem with boolean alternation in react,
- React Native pass parameters through map function
- How to upgrade a React project built with create-react-app to the next create-react-app version?
- AntD Icon should have type prop or component prop error using in Tab component
- MUI: The `fade` color utility was renamed to `alpha` to better describe its functionality. (material-table)
- is it possible to retrieve state from Redux store for a particular review comments
- Bad replace url with query params react router 5.2
- Animating newly appended element in React.js
- how to disable future time in material-ui KeyboardDateTimePicker in reactjs
- Delete API call in Reactjs
- How do I clear Bootstrap 4 errors after I submit my React form?
- React Update a list with New Items But Ids might repeat