The M
The M

Reputation: 661

Delete object by ID from nested object in the redux state Javascript / ES6

I am trying to remove an object from a nested object items in the redux state. I can only manage to remove the values instead of the actually key. I cannot filter it since it's not an array. I though maybe Object.keys(state.items[or_id]).reduce() might be a option?

The state:

items: {
      'b0ad5c5c-5cf4-40b5-9bc9-87f773ba3c06': {
        '7e8557dc-9352-4dea-a062-0a1d43371698': {
          value: {
            id: '7e8557dc-9352-4dea-a062-0a1d43371698',
            expires_on: '2020-11-19T14:22:18.182000+00:00'
          }
        },
        '7e8557dc-9352-4dea-a062-0a1d43371692': {
          value: {
            id: '7e8557dc-9352-4dea-a062-0a1d43371692',
            expires_on: '2021-11-19T14:22:18.182000+00:00'
          }
        }
      }
    },

The reducer:

if(type === DELETE){
     const { or_id, in_id } = payload;
     return {
          ...state,
          items: {
            ...state.items,
            [or_id]: {
              ...state.items[or_id],
              [in_id]: {},
            },
          },
        };
}

If I use this method above the key still exists in the state.

 items: {
      'b0ad5c5c-5cf4-40b5-9bc9-87f773ba3c06': {
        '7e8557dc-9352-4dea-a062-0a1d43371698': {},
        '7e8557dc-9352-4dea-a062-0a1d43371692': {
          value: {
            id: '7e8557dc-9352-4dea-a062-0a1d43371692',
            expires_on: '2021-11-19T14:22:18.182000+00:00'
          }
        }
      }

Expected result (1 item less):

 items: {
      'b0ad5c5c-5cf4-40b5-9bc9-87f773ba3c06': {
        '7e8557dc-9352-4dea-a062-0a1d43371692': {
          value: {
            id: '7e8557dc-9352-4dea-a062-0a1d43371692',
            expires_on: '2021-11-19T14:22:18.182000+00:00'
          }
        }
      }

Upvotes: 1

Views: 639

Answers (1)

HMR
HMR

Reputation: 39360

You can do it in several ways:

Using spread and rest

const removeKey = (key, object) => {
  //using spread and rest
  const { [key]: gone, ...rest } = object;
  return rest;
};
console.log(
  'remove key "W"',
  removeKey('W', { ok: 88, W: 'gone' })
);

Using Object.fromEntries

//using Object.fromEntries
const removeKey = (key, object) =>
  Object.fromEntries(
    Object.entries(object).filter(([k]) => k !== key)
  );
console.log(
  'remove key "W"',
  removeKey('W', { ok: 88, W: 'gone' })
);

Using delete on a shallow copy

//using delete on shallow copy
const removeKey = (key, object) => {
  const copy = { ...object };
  delete copy[key];
  return copy;
};
console.log(
  'remove key "W"',
  removeKey('W', { ok: 88, W: 'gone' })
);

Upvotes: 3

Related Questions