0

I have a jQuery object with key value pairs, an example below:

{'primary-buyer': 
       {'first_name': 'NAME', 
        'last_name': 'NAME', 
       }
}, 

What I'm trying to accomplish is replacing the underscore '_' in each of the object keys to a dash '-'.

I've written an $.each statement that accomplished this but I don't know how to assign the new keys to the existing object so I can access it outside of the $.each statement.

        let customers = JSON.parse($.cookie('customers'));
        $.each(customers, function(key, value) {
            $.each(value, function(k, v) {
                if (k.indexOf('_') >= 0) {
                    k = k.replace('_', '-');
                }
            }) 
        })

When logging 'k' inside of the $.each it comes out how I want it, e.g. 'first-name', but if I try to log customers outside of the $.each it still has the original format, e.g. 'first_name'.

1 Answer 1

1

You can't modify a key directly. You have to assign a new key with the same value and delete the old key.

let customers = {
  'primary-buyer': {
    'first_name': 'NAME',
    'last_name': 'NAME',
  }
};

$.each(customers, function(key, value) {
  $.each(value, function(k, v) {
    if (k.includes('_')) {
      delete value[k];
      k = k.replaceAll('_', '-');
      value[k] = v;
    }
  })
});

console.log(customers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You should use replaceAll() in case there are multiple _ in the original key.

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

Comments

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.