admin管理员组

文章数量:1241099

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 :)

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 :)

Share Improve this question asked Feb 3, 2016 at 11:09 stackunderflowstackunderflow 1,7146 gold badges25 silver badges40 bronze badges 11
  • 2 lodash./docs#invert – georg Commented Feb 3, 2016 at 11:11
  • Thanks, does this also work with nested objects? – stackunderflow Commented Feb 3, 2016 at 11:19
  • Reversing keys and values in an object sounds like something you would only want to if your program design is flawed. May I ask what this should be used for? – Tomalak Commented Feb 3, 2016 at 11:37
  • 1 I am having to map a new data schematic to a legacy system, so it's not really poor program design, just a way for our new system to work with our existing one. So in this case, your assumption is flawed :) – stackunderflow Commented Feb 3, 2016 at 11:41
  • @Tomalak after racking my brain for a while now and not seeing any other way of actually doing this mapping between two systems, with the upmost respect can you please explain how this is a flawed design? – stackunderflow Commented Feb 3, 2016 at 14:57
 |  Show 6 more ments

1 Answer 1

Reset to default 14

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./ajax/libs/lodash.js/4.2.0/lodash.min.js"></script>

本文标签: javascriptLodash method for reversing key values in objectStack Overflow