0

I have a user with a favorites array

I am trying to concat an item to the favorites field.

Here I assign the user to userToChange variable

const userToChange = action.data.user;

And here I concat a 'card to the user's favorites field

const changedUserFavorites = userToChange.favorites.concat(action.data.card);

I need to pass the updated user field to an axios update call. I have tried to concat the user and the updated favorites field like this.

 const changedUser = userToChange.concat(changedUserFavorites);

but I am getting an error: ×

Unhandled Rejection (TypeError): userToChange.concat is not a function

I suspect this might be due to the fact that userToChange is an object

Here is what userToChange looks like:

User to Change 
Object
favorites: [Array(1)]
firstName: "phil"
id: "5de9930fedc70846747305f6"
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InBoaWwiLCJmaXJzdE5hbWUiOiJwaGlsIiwiaWF0IjoxNTc1NTkwNDkwfQ.SYoApD4FUuXDEhjWSDBg0_gkKmf7a2FHm5Yifu2yhgw"
username: "phil"
__proto__: Object

and changedUserFavorites is an Array.

Thus, I just wonder how can I put the two together given that one field is an object?

2
  • 1
    Object.assign can be your friend. Commented Dec 6, 2019 at 1:09
  • 1
    You cannot .concat() to an object. Commented Dec 6, 2019 at 1:09

1 Answer 1

2

For objects, you can use Object.assign to append properties onto an existing object.

let myObj = { a: 1 }
let newObj = { b: 1 }
Object.assign(myObj, newObj)
///myObj = { a: 1, b:1 }

For arrays, you have the Array.prototype.concat method.

let myArr = [1, 2]
myArr.concat([3, 4])
//myArr = [1, 2, 3, 4]

MDN

Sign up to request clarification or add additional context in comments.

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.