I am facing a particular problem that I need to change the structure of a object like:
customerPayload = {
name: 'Name must remain',
billing_address_street: 'Electric Avenue',
billing_address_number: 222,
shipping_address_street: 'Avenue 1',
shipping_address_number: 1337
};
into this:
customerPayload = {
name: 'Name must remain',
billing_address: {
street: 'Electric Avenue',
number: 222
},
shipping_address: {
street: 'Avenue 1',
number: 1337
}
};
I tried something like this:
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
}
}
But the result is an object with only the last changed properties:
customerPayload = {
billing_address: {
number: 222
},
shipping_address: {
street: 'Avenue 1'
}
};
Please, any help?
customerPayloadis a requested body in my server and I cant change the properties names =/