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
1 Answer
Reset to default 14invert
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
版权声明:本文标题:javascript - Lodash method for reversing key: values in object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740032992a2221323.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论