gpt4 book ai didi

javascript - 如何将多个对象合并为单独的对象

转载 作者:行者123 更新时间:2023-12-02 21:10:05 24 4
gpt4 key购买 nike

我正在使用 Vue.js,我有 2 个对象,我想将它们组合在一起,但将它们分开。

我尝试使用诸如 var obj1 = {...obj2, ...obj3} 之类的扩展,但意识到这会覆盖值,因为名称相同。我将帐单地址信息更改为在其前面添加“帐单”,并再次使用相同的过程,它只是一个很长的列表,对我来说不是很干净。

下面是我尝试组合的 2 个对象。

deliveryAddress: {
firstName: null,
lastName: null,
companyName: null,
jobTitle: null,
address1: null,
address2: null,
city: null,
country: null,
province: null,
region: null,
state: null,
zipCode: null,
phoneNumber: null,
email: null
},
billingAddress: {
billingDifferentFromDelivery: false,
billingAddress1: null,
billingAddress2: null,
billingCity: null,
billingCountry: null,
billingState: null,
billingProvince: null,
billingZipCode: null,
}

我想将它们组合为一个对象与两个对象或一个数组与两个对象。也许有类似的东西

var addressInformation = {
deliveryAddress: {
firstName: null,
lastName: null,
companyName: null,
jobTitle: null,
address1: null,
address2: null,
city: null,
country: null,
province: null,
region: null,
state: null,
zipCode: null,
phoneNumber: null,
email: null
},
billingAddress: {
billingDifferentFromDelivery: false,
billingAddress1: null,
billingAddress2: null,
billingCity: null,
billingCountry: null,
billingState: null,
billingProvince: null,
billingZipCode: null,
}
}

var addressInformation = [{
deliveryAddress: {
firstName: null,
lastName: null,
companyName: null,
jobTitle: null,
address1: null,
address2: null,
city: null,
country: null,
province: null,
region: null,
state: null,
zipCode: null,
phoneNumber: null,
email: null
},
billingAddress: {
billingDifferentFromDelivery: false,
billingAddress1: null,
billingAddress2: null,
billingCity: null,
billingCountry: null,
billingState: null,
billingProvince: null,
billingZipCode: null,
}
}]

这可能吗?组合对象时有更好的方法来清理它吗?

最佳答案

需要单独指定属性名称

 let addressInformation = {deliveryAddress : ...obj1, billingAddress: ...obj2}

 let addressInformation = [{deliveryAddress : ...obj1}, {billingAddress: ...obj2}]

或者,如果您不需要新副本,那么您也可以执行类似的操作

  let addressInformation = {deliveryAddress, billingAddress}

关于javascript - 如何将多个对象合并为单独的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61122499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com