1

I'm trying to remove "personal_" from any object key names.

I tried running a loop and getting the object key name, then using the replace function on it but it doesn't remove the personal_.

var object = {
  active: false,
  personal_user_metadata: {
    first_name: 'jon',
    last_name: 'doe',
 },
  personal_app_metadata: {
   data: 'blah',
  },
  email: 'jondoe@example.com'
}

for(name in object){
   name.replace('personal_', '')
}

console.log(object)
Stark
  • 572
  • 10
  • 24

2 Answers2

2

below snippet will do the trick.

    var obj = {
      active: false,
      personal_user_metadata: {
        first_name: 'jon',
        last_name: 'doe',
     },
      personal_app_metadata: {
       data: 'blah',
      },
      email: 'jondoe@example.com'
    }

    for(name in obj){
      if(name.startsWith('personal_')){
        var replaced_key = name.replace('personal_', '');
        obj[replaced_key] = obj[name];
        delete obj[name];
      }
    }

    console.log(obj)

what is wrong with your code is, you are just doing a string manipulation, but do not assign those modified keys as keys to that object.

marmeladze
  • 6,468
  • 3
  • 24
  • 45
  • I understood your point about not assigning the modified keys back to the object, but all the rest of the key's gets removed, in your example. – Stark May 20 '18 at 19:06
  • sorry, i've just missed one thing. i thought all keys has `personal` prefix. i've fixed it now – marmeladze May 20 '18 at 19:07
2

Same as @marmeladze, but with higher order functions

const object = {
  active: false,
  personal_user_metadata: {
    first_name: 'jon',
    last_name: 'doe',
 },
  personal_app_metadata: {
   data: 'blah',
  },
  email: 'jondoe@example.com'
}

Object.keys(object)
  .filter(key => key.startsWith(`personal_`))
  .forEach(key => {
     object[key.replace(`personal_`, ``)] = object[key];
     delete object[key];
  })

console.log(object)
Ritwick Dey
  • 18,464
  • 3
  • 24
  • 37