How to generate an key-values inversed object in JavaScript? -


update

i have adjusted/corrected example objects, because contained error before.

i have mapping object looks this:

var atob = {   "amore"   : "love",   "alimenti": "food",   "bier"    : "beer" }; 

which allows map 1 way i.e. atob["love"] yields "amore". add inverse manualy i.e.

var btoa = {   "love": "amore",   "food": "alimenti",   "beer": "bier" }; 

anyway troublesome 2 objects in sync , create btoa programmatically in javascript. there sort of function xyz() yields var btoa = xyz(atob);?

the example above can extended include problem (e.g. if have "beer")

var atob = {   "amore"   : "love",   "alimenti": "food",   "bier"    : "beer"   "cerveza" : "beer",   "pivo"    : "beer",   "birra"   : "beer",   "cerveja" : "beer" }; 

as not 1-to-1 mapping. in amateuer math terms not inversible function?

to make things more complicated have recipe desaster.

var makestuff = {   "agriculture": "food",   "hops" : {     "water": {       "malt": "beer"},     "malt": {       "water": "beer"}},   "water" : {     "hops": {       "malt": "beer"},     "malt": {       "hops": "beer"}},   "malt" : {     "water": {       "hops": "beer"},     "hops": {       "water": "beer"}}   }; 

inversing nested javascript object, seems more challanging such xyz() function. anyway maybe there such xyz() function, glad accept answer question

very simple. following code inverse key, value.

var inverse= (function inv(param){  for(var attr in param) {     if(param.hasownproperty(attr)) {         if(typeof param[attr]==="string") {             param[param[attr]] = attr;             delete param[attr];                         } else if (object.prototype.tostring.call(param[attr]) === "[object object]") {             param[attr] = inv(param[attr]);         }     } } return param; }); 

to result other object, initialize empty , assign it. like

var btoa = {}; btoa = inverse(atob); 

and, json:

var atob = {   "love": "amore",   "food": "alimenti",   "beer": "bier",   "beer": "cerveza",   "beer": "pivo",   "beer": "birra",   "beer": "cerveja", }; 

has 3 attributes because json dictionary data structure: new key replace old one. above json like:

{love: "amore", food: "alimenti", beer: "cerveja"} 

so, inverting above given json (atob) result in inversion of 3 properties, , final result be:

{amore: "love", alimenti: "food", cerveja: "beer"} 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -