Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove the space in keys in a nested object using javascript

Tags:

javascript

I want to replace the whitespace of keys 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 did is:

 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',
  }

What i want is:

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

What am i doing wrong here??

like image 827
Sunil Lama Avatar asked Apr 21 '17 08:04

Sunil Lama


1 Answers

You could 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; }
like image 174
Nina Scholz Avatar answered Nov 16 '22 11:11

Nina Scholz