[英]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在这里,我将用户分配给
userToChange
变量
const userToChange = action.data.user;
And here I concat a 'card to the user's favorites
field在这里,我将一张“卡片连接到用户的
favorites
字段
const changedUserFavorites = userToChange.favorites.concat(action.data.card);
I need to pass the updated user field to an axios update call.我需要将更新的用户字段传递给 axios 更新调用。 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我怀疑这可能是因为 userToChange 是一个对象
Here is what userToChange
looks like:这是
userToChange
样子:
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.而
changedUserFavorites
是一个数组。
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.对于对象,您可以使用
Object.assign
将属性附加到现有对象上。
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.对于数组,您有
Array.prototype.concat
方法。
let myArr = [1, 2]
myArr.concat([3, 4])
//myArr = [1, 2, 3, 4]
MDN MDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.