kingloui
kingloui

Reputation: 161

How do you move an object from one array to another array by feature?

I am trying to move an object from one array to another. Think of it like adding / moving a friend from non-friend to friend. I have two arrays, which can be seen below, and I am trying to move an object (i.e. a friend) from possible to current via it's 'id'. In the below example, I am trying to move Parker from possible to current with id = 2.

state = {
    current: [
        {
            id: 1,
            name: 'peter'
        }
    ],
    possible: [
        {
            id: 2,
            name: 'parker'
        }
    ]
}


function addFriend(state, action) {
  const { current, possible } = state;
  const addedFriend = Object.assign(
    {},
    state.possible.splice(action.payload.index, 1)
  );

  current.push(addedFriend);

  const newState = { current, possible };
  return newState;
}

Upvotes: 0

Views: 1009

Answers (2)

Prasanna
Prasanna

Reputation: 4656

It is not that time-efficient if you want a fast running code. But it follows immutability.

We just ignore the item from possible, and add it to current.

state = {
    current: [
        {
            id: 1,
            name: 'peter'
        }
    ],
    possible: [
        {
            id: 2,
            name: 'parker'
        }
    ]
}


function addFriend(state, action) {
  const { current, possible } = state;
  return {
    ...state,
    current: current.concat(possible[action.payload.index]),
    possible: possible.filter((_, index) => index !== action.payload.index)
  }
}

state = addFriend(state, {payload: {index: 0}})
console.log(state)

Upvotes: 0

Barmar
Barmar

Reputation: 782158

Since you can remove multiple elements with splice(), it returns an array. Index the result to get the specific object. You don't need to use Object.assign(), that just copies the value (which just converts the array into an object whose properties are the array indexes).

var state = {
    current: [
        {
            id: 1,
            name: 'peter'
        }
    ],
    possible: [
        {
            id: 2,
            name: 'parker'
        }
    ]
};

function addFriend(state, action) {
  const { current, possible } = state;
  const addedFriend = state.possible.splice(action.payload.index, 1)[0];

  current.push(addedFriend);

  const newState = { current, possible };
  return newState;
}

state = addFriend(state, {payload: { index: 0 }});
console.log(state);

I'm not sure why you're returning a new state object, since you're modifying the old state in place.

Upvotes: 1

Related Questions