Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash method for reversing key: values in object

Anyway one might be able to turn the following;

{
    "ID": "id"
    "Name": "name"
}

into;

{
    "id": "ID",
    "name": "Name"
}

Using lodash? I'm specifically looking for something along the lines of;

var newObj = _.reverseMap(oldObj);

Thanks :)

like image 973
stackunderflow Avatar asked Feb 03 '16 11:02

stackunderflow


1 Answers

invert works fine for flat objects, if you want it to be nested, you need something like this:

var deepInvert = function(obj) {
    return _.transform(obj, function(res, val, key) {
        if(_.isPlainObject(val)) {
            res[key] = deepInvert(val);
        } else {
            res[val] = key;
        }
    });
};

//

var a = {
    x: 1,
    y: 2,
    nested: {
        a: 8,
        b: 9
    }
};

var b = deepInvert(a);
document.write('<pre>'+JSON.stringify(b,0,3));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.2.0/lodash.min.js"></script>
like image 50
georg Avatar answered Oct 12 '22 22:10

georg