How to remove a key value pair from object while updating values of remaining objects?

const initialState = {
    loading: null,
    error: null,
    lineItems: [
         {
             id: 1, 
             product_name: "Elbow 15", 
             product_disc: 1, 
             sub_total: 5548.95, 
             product_unit: "Nos", 
             …
         }
         {
             id: 2, 
             product_name: "Tee 15", 
             product_disc: 3, 
             sub_total: 24.25, 
             product_unit: "Nos", 
             …
         }
         {
             id: 3, 
             product_name: "", 
             product_disc: 0, 
             sub_total: 0
         }
    ]

lineItems represent rows in a grid (I am using react-data-grid)

id property values are used to populate the first column ("Serial Number") of the grid

If a user deletes a row (e.g. middle object in the above case), how to update the above object, so that is becomes

  lineItems: [
        {
            id: 1, 
            product_name: "Elbow 15", 
            product_disc: 1, 
            sub_total: 5548.95, 
            product_unit: "Nos", 
            …
        }
        {
            id: 2, 
            product_name: "", 
            product_disc: 0, 
            sub_total: 0
        }
    ]

2 answers

  • answered 2018-11-08 05:39 Barmar

    You can use delete to remove a property from an object. Then you'll need to loop through the remaining properties and update their keys and the id properties within them.

    function removeLineItem(state, index) {
      delete state.lineItems[index];
      Object.keys(state.lineItems).forEach(k => {
        if (state.lineItems[k].id > index) {
          state.lineItems[k].id = k - 1; // decrement id
          state.lineItems[k - 1] = state.lineItems[k]; // decrement key
          delete state.lineItems[k]; // remove old key
        }
      });
    }
    
    const initialState = {
      loading: null,
      error: null,
      lineItems: {
        0: {
          id: 1,
          product_name: "Elbow 15",
          product_disc: 1,
          sub_total: 5548.95,
          product_unit: "Nos",
        },
        1: {
          id: 2,
          product_name: "Tee 15",
          product_disc: 3,
          sub_total: 24.25,
          product_unit: "Nos",
        },
        2: {
          id: 3,
          product_name: "",
          product_disc: 0,
          sub_total: 0
        }
      }
    };
    
    removeLineItem(initialState, 1);
    console.log(initialState);

  • answered 2018-11-08 06:24 Ammar Tariq

    You can use delete keyword to delete specific key from your object.

    delete object['key']