how to delete nested object in React with spread function

Viewed 496

I am working on a simple cart function with react-redux, and I have an object that is structured as below:

{
     0: { // product ID
       "S" : 1, //product variant and item count
       "M" : 1  
     },
     1: {
       "L":1
       "XL": 5
     },
}

I wanted to remove the property based on user action but I was not able to achieve that so far.

Attempt 1: delete function will remove everything within the state instead of removing the selected property.

    case REMOVE_PRODUCT_FROM_CART:
      let newObject = Object.assign({}, state)
      return delete newObject[productId][varient];

Attempt 2: only managed to set the property to null but still not able to remove the item.

    case REMOVE_PRODUCT_FROM_CART:
      return {...state,
        [productId]: {
          // check if property exists
          ...(state?.[productId] ?? {}),
          [varient]: null
       }

Is there any way to remove the desired property with the spread operator?

2 Answers

Here is one way to do it:

case REMOVE_PRODUCT_FROM_CART:
  const newObject = {...state[productId]}
  delete newObject[varient]
  return {...state, [productId]:newObject}

Here is another way to do it:

const state = {
  22: {
    ok: 88,
    remove: 22,
  },
};
const productId = 22;
const varient = 'remove';
const { [varient]: ignore, ...product } = state[productId];
console.log('new state', {
  ...state,
  [productId]: product,
});

Here is another option using Object.entries and Object.fromEntries

const state = {
  pId: {
    k1: 'v1',
    k2: 'v2',
    k3: 'v3',
  },
};

const reducer = (productId, variant) => {
  return {
    ...state,
    [productId]: Object.fromEntries(
      Object
      .entries(state[productId])
      .filter(([key, val]) => key !== variant)
    ),
  }
}
console.log(reducer('pId', 'k2'))

Related