JSFiddle - React, Tailwind, and code Playground

by kmendes

JavaScript

input = {a: 10, 
         b: { c: 11, d: 12 }, 
         c: { d: 13, b: 14 },
         x: { y: { z: 99 }}}

// Details:          
// If an item does not have a 2nd level dict, then it should be preserved as a toplevel item. 
// If there's a conflict, then an assertion should be raised.  (i.e. {a:10, b: {a:12}} ) 

// Please implement the swap_keys method called above. 
function swap_keys(inputObject){
    var output = {};
    for(var key in inputObject){
        if(isNaN(inputObject[key])){
            for(var innerKey in inputObject[key]){
                //var newKey = inputObject[key];
               if(typeof output[innerKey] == "undefined")
                   output[innerKey] = { };
               output[innerKey][key] = inputObject[key][innerKey];
            }
        }else{
            output[key] = inputObject[key];
        }
    }
    return output;
}

var output = swap_keys(input); 
console.dir(output);
/*
console.log(output[a] == input[a])
console.log(output[c][b] == input[b][c])
console.log(output[d][b] == input[b][d])
console.log(output[y][x] == input[x][y]) // a dict 
console.log(output[y][x][z] == 99)*/