4

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?

2
  • 1
    Why not doing it manually it will take 4 lines of code I think! Commented Feb 21, 2017 at 14:59
  • 1
    The object customerPayload is a requested body in my server and I cant change the properties names =/ Commented Feb 21, 2017 at 15:02

1 Answer 1

3

You can use reduce() to return new object.

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)

Sign up to request clarification or add additional context in comments.

3 Comments

What are the rules to split the string? I am not familiar with regex. This is also breaking a property named invoice_template and this should remain as it is on new object.
It breaks string at last _.
You need to define logic how are you splitting string but lets say you only want to split string if it has more then 1 _ you can use this jsfiddle.net/Lg0wyt9u/1591

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.