Lodash method for reversing key: values in object Lodash method for reversing key: values in object node.js node.js

Lodash method for reversing key: values in object


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>