Search code examples
javascriptarraysreactjsunderscore.jslodash

How to remove an element from an array in a nested object? (lodash)


I had an object like

data: {
    registrationNumber: 'MH1234',
    type: 'xyz',
    driver: {
      user: {
        firstName: 'xyz',
        lastName: 'abc',
        email: 'xyz',
        phone: 1234,
        city: 'random',
        dateOfBirth: new Date(),
        groups: [1]
      }
    },
    owner: {
      user: {
        firstName: 'xyz',
        lastName: 'abc',
        email: 'xyz',
        phone: '1234',
        city: 'random',
        groups: [1, 2]
      },
      kyc: [
        {
          method: 'xyz',
          id: 'abcd'
        },
        {
          method: 'xyz',
          id: 'abcd'
        }
      ]
    }
  }

how can i remove the element at path data.owner.kyc.0 ?

I have tried using _.unset() but it is not ideal since the array still shows 2 elements after deletion


Solution

  • You don't need lodash to accomplish this.

    With .shift() to remove first element from array.

    let newData = {...data}
    
    newData.owner.kyc.shift()
    

    With .splice() to remove elements from a certain point.

    let newData = {...data}
    
    newData.owner.kyc.splice(0, 1)
    

    With .filter() to remove items that don't match a specified condition

    let newData = {...data}
    
    newData.owner.kyc = newData.owner.kyc.filter((item, index) => {
       return index !== 0
    })
    

    Since you're using React, you would want to have this data in component-state so that when you actually remove something from the array, the App updates to reflect the new results.

    See sandbox: https://codesandbox.io/s/mystifying-fog-2yhwd

    class App extends React.Component {
      state = {
        data: data
      };
    
      removeFirstItem = () => {
        const { data } = this.state;
    
        let newData = { ...data };
    
        newData.owner.kyc.shift();
    
        this.setState({
          data: newData
        });
      };
    
      render() {
        const { data } = this.state;
        return (
          <div>
            <h4>Car Info:</h4>
            <div>
              KYC:
              {data.owner.kyc.map((item, index) => {
                return (
                  <div>
                    <span>{index + 1}) </span>
                    {item.id}
                  </div>
                );
              })}
            </div>
            <button onClick={this.removeFirstItem}>Remove first item</button>
          </div>
        );
      }
    }