2

I'd like to remove a nested object based on the id is equal to a passed prop. At the moment, the entire object is replaced. I'm missing something, when trying to update the state using useState probably with the way I'm looping my object?

UPDATE: The question was closed in response to available answers for updating nested objects. This question involves arrays which I believe are part of the issue at hand. Please note the difference in nature in this question with the forEach. Perhaps a return statement is required, or a different approach to the filtering on id..

my initial object looks like this:

{
  "some_id1": [
    {
      "id": 93979,
      // MORE STUFF
   
    },
    {
      "id": 93978,
      // MORE STUFF
    }
  ],
  "some_id2": [
    {
      "id": 93961,
      // MORE STUFF
    },
    {
      "id": 93960,
      // MORE STUFF
    }
  ]
}

and I go through each item as such:

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,
                        [key]: {
                            ...prevState[key],
                            [x.id]: undefined
                        }
                    }))
                }
            })
        }
0

4 Answers 4

3
+25

There are 3 problems in your code:

  1. You are setting the value of key to an object while the items is expected to have an array to ids.
// current
[key]: {
 ...prevState[key],
 [x.id]: undefined
}

// expected
[key]: prevState[key].filter(item => item.id === matchingId)
  1. 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
  1. To make your code more readable, it is expected to manipulate the entire object items and then, set it to the state once using setItems - in contrast to calling setItems 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);
1
  • Was away on holiday and just got back to this. Thank you everyone.
    – van
    Aug 23, 2021 at 16:50
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}))

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)

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.