LarsRefsgaard
LarsRefsgaard

Reputation: 11

Changing all keys of an object recursively TS

I want to change all keys of an object according to a dictionary, for example:

const result: Object = {
    "_id": "010973",
    "local": {
        "prod": {
            "unit": 1,
            "vol": 1174.5,
        }, "pack": {
            "vol": 16226,
        }
    }, "catalogue": {
        "thumb": "http://www.apimages.com/Images/Ap_Creative_Stock_Header.jpg",
    }
};

const dict: Object = {
    '_id': 'Product number',
    'local.prod' : 'Product information',
    'local.prod.vol': 'Product vol (cm3)',
    'local.prod.unit': 'Product unit (qty)',
    'local.pack.vol': 'Package vol (cm3)',
    'catalogue.thumb': 'Image URL'
};

Where I want the end result to be something like

{
    "Product number": "010973",
    "local": {
        "Product information": {
            "Product unit (qty)": 1,
            "Product vol (cm3)": 1174.5,
        }, "pack": {
            "Package vol (cm3)": 16226,
        }
    }, "catalogue": {
        "Image URL": "http://www.apimages.com/Images/Ap_Creative_Stock_Header.jpg",
    }
};

For now I have

const changeKeys = (obj: Object, dictionary: Object): void => {
    Object.keys(obj).forEach(key => {
        obj[dictionary[key]] = obj[key]
    })

};
changeKeys(result, dict);

which will only change the first layer, so _id would become product number. I guess I just have to do some sort of recursion on the result object, but I can't seem to make it work, and also some error handling for when it the key isn't able to be translated.

Upvotes: 1

Views: 149

Answers (1)

SalientBrain
SalientBrain

Reputation: 2541

I can suggest you to use lodash without reinventing the wheel. It has a lot of HQ useful features for modern apps.

import * as _ from "lodash";
    
for(const key of Object.keys(dict)){
  if(_.get(result, key) != undefined){
    _.set(result, key, dict[key]);
  }
}
console.log(result);

Upvotes: 1

Related Questions