2

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

Malik Bagwala
  • 2,695
  • 7
  • 23
  • 38

3 Answers3

0

You can use _.remove or _.filter.

Please refer this example

GRS
  • 1,829
  • 1
  • 9
  • 23
0

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>
    );
  }
}
Chris Ngo
  • 15,460
  • 3
  • 23
  • 46
0

You can use a Array prototype method itself, if you want to remove from the front

Array.prototype.shift.apply(data.owner.kyc,null)
Arun-G
  • 111
  • 7