gpt4 book ai didi

javascript - 在 Javascript 中更改对象结构和属性

转载 作者:行者123 更新时间:2023-11-29 14:38:21 24 4
gpt4 key购买 nike

我面临一个特殊的问题,我需要更改对象的结构,例如:

customerPayload = {
name: 'Name must remain',
billing_address_street: 'Electric Avenue',
billing_address_number: 222,
shipping_address_street: 'Avenue 1',
shipping_address_number: 1337
};

进入这个:

customerPayload = {
name: 'Name must remain',
billing_address: {
street: 'Electric Avenue',
number: 222
},
shipping_address: {
street: 'Avenue 1',
number: 1337
}
};

我试过这样的:

for (var p in customerPayload) {
if (customerPayload.hasOwnProperty(p)) {
if (p.includes('billing')) {
var b = p.substr(0, 15) + '.' + p.substr(15 + 1);
var bAddress = b.split('.')[0];
var childProp = b.split('.')[1];
newCustomerPayload[bAddress] = {
[childProp]: customerPayload[p]
};
}
// else if shipping ... same thing
}
}

但结果是一个只有最后更改的属性的对象:

 customerPayload = {
billing_address: {
number: 222
},
shipping_address: {
street: 'Avenue 1'
}
};

请问有什么帮助吗?

最佳答案

您可以使用 reduce() 返回新对象。

var data = {
name: 'Name must remain',
billing_address_street: 'Electric Avenue',
billing_address_number: 222,
shipping_address_street: 'Avenue 1',
shipping_address_number: 1337
};

var result = Object.keys(data).reduce(function(r, e) {
if (!e.match('_')) r[e] = data[e]
else {
var key = e.split(/_([^_]*)$/)
if (!r[key[0]]) r[key[0]] = {}
r[key[0]][key[1]] = data[e]
}
return r;
}, {})

console.log(result)

关于javascript - 在 Javascript 中更改对象结构和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42370704/

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