简体   繁体   中英

How To concat an Object and Array in Javascript?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM