Fred J. Fred J. - 4 years ago 83
Javascript Question

Change property name of objects

An array of about 5 or more javascript objects in this format

[{'a':'man', 'age':'35'},{'b':'woman', 'age':'30'}]
needs to be converted to

What is an efficient way to do it?


Also the input array may be like this where the keys are switched around:
[{'a':'man', 'age':'35'},{'age':'30', 'b':'woman'}]
where a, b, ... could be anything and the objects in the array could up to 10 objects.

Answer Source

You could iterate the array and iterate the keys and change only the unknown key to gender.

var data = [{ a: 'man', age: '35' }, { b: 'woman', age: '30' }];

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if (k !== 'age') {
            o.gender = o[k];
            delete o[k];


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download