Home > Software design >  jQuery change object Key in $.each Statement
jQuery change object Key in $.each Statement

Time:11-18

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'.

CodePudding user response:

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.

  • Related