1

I have a weird situation. I have 2 objects: state.result which is an array of objects and data.catalogs which is an array of objects similar to state.result.

I want to create a pure function to return copy of both of them merged (in a redux reducer). If I run:

 {
    ...state,
    result: {...state.result, ...data.catalogs}
  }

Everything is hunkey dorey and the 4 items in state.result are merged with the 1 item in data.catalogs leaving me with a return value of 4 items. The problem is I want an array of items and this gives me and object with 4 properties containg the items.

If I run:

  {
    ...state,
    result: [...state.result, ...data.catalogs]
  }

It gives me an array of items like I want but instead of merging them, it appends them so I get an array of 5 items (a duplicate of the item in state.result and data.catalogs).

Why is this happening and how can I merge items within an array?

3
  • 1
    I didn't get.. state.result contains only data.catalogs ? Show how your state looks like ( the relevant part ) Commented Sep 1, 2018 at 20:29
  • Oh sorry state is empty right now Commented Sep 1, 2018 at 20:33
  • Array spead operation can not merge, because it has no keys to merge with. You can check out Dan Abramov's tutorial on working with array in reducers here: github.com/RyoIkarashi/redux-tutorial-by-dan-abramov/blob/… Commented Sep 1, 2018 at 20:36

2 Answers 2

2

You'll have to handle merging of arrays separately

const x = [{id: 1}, {id: 2, name: 'two'}, {}];
const y = [{name: 'one'}, {}, {id: 3, name: 'three'}];

const z = x.map((e, index) => Object.assign({}, {...e, ...y[index]}));

// z = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}]
Sign up to request clarification or add additional context in comments.

Comments

1
    {
    ...state,
    result: {...state.result, ...data.catalogs}
  }

How about using that then taking the values you want out of it with Object.values(results) you can .map() it if you need to as well.

I hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.