Remove space in keys in nested object with javascript

I want to replace the key space in a nested object. I have an object as follows:

     var data = 
 { 'General Information':
             { 'Referral No': '123123',
               Marketer: '',
               Casemanager: 'Alexis Clark',
               'CM Username': '',
               VOC: '',
               'Foreign Voluntary': '',
            },
     'Account Name': 'CTS Health',
    }

What I've done:

 for (var k in data) {
    if (k.replace(/\s/g, '') !== k) {
        data[k.replace(/\s/g, '')] = data[k];
        if (data[k] !== null && typeof data[k] === 'object') {
            for (var x in data[k]) {
                if (x.replace(/\s/g, '') !== x) {
                    data[k][x.replace(/\s/g, '')] = data[k][x];
                    delete data[k][x];
                }
            }
        }
        delete data[k];
    }
}

I get this:

{ GeneralInformation:
         { 'Referral No': '123123',
           Marketer: '',
           Casemanager: 'Alexis Clark',
           'CM Username': '',
           VOC: '',
           'Foreign Voluntary': '',
        },
    AccountName: 'CTS Health',
  }

I want:

{ GeneralInformation:
         { ReferralNo: '123123',
           Marketer: '',
           Casemanager: 'Alexis Clark',
           CMUsername: '',
           VOC: '',
           ForeignVoluntary: '',
        },
    AccountName: 'CTS Health',
  }

What am I doing wrong here?

+6
source share
3 answers

You can use an iterative and recursive approach for nested objects.

function replaceKeys(object) {
    Object.keys(object).forEach(function (key) {
        var newKey = key.replace(/\s+/g, '');
        if (object[key] && typeof object[key] === 'object') {
            replaceKeys(object[key]);
        }
        if (key !== newKey) {
            object[newKey] = object[key];
            delete object[key];
        }
    });
}


var data = { 'General Information': { 'Referral No': '123123', Marketer: '', Casemanager: 'Alexis Clark', 'CM Username': '', VOC: '', 'Foreign Voluntary': '', }, 'Account Name': 'CTS Health' };

replaceKeys(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result
+5
source

Try a recursive approach.

var replaceSpace = function (obj) {
  Object.keys(obj).forEach(function(key){
    var newKey = key.split(' ').join('');
    if(object[key] && typeof obj[key] === "object"){
      obj[newKey] = replaceSpace(obj[key])
    }else{
      obj[newKey] = obj[key]
    }

    if(key != newKey)
      delete obj[key]
  })
  return obj
}
0
source

We can create a new object instead of mutating an existing one. This simplifies testing and also reduces the likelihood of errors due to sharing.

function withNormalizedKeys(o) {
  return Object.entries(o)
    .map(([key, value]) => [key.replace(/\s+/g, ''), value])
    .reduce((result, [normalizedKey, value]) => {
      result[normalizedKey] =
      value && typeof value === 'object'
      ? withNormalizedKeys(value)
      : value;
    return result;
  }, {});
}

const data = {
  'General Information': {
    'Referral No': '123123',
    Marketer: '',
    Casemanager: 'Alexis Clark',
    'CM Username': '',
    VOC: '',
    'Foreign Voluntary': ''
  },
  'Account Name': 'CTS Health'
};
const normalized = withNormalizedKeys(data);
console.log(normalized);
Run codeHide result
-2
source

Source: https://habr.com/ru/post/1016671/


All Articles