Back to Bloginterview

Convert JSON key to values (vice-versa)

A simple way to convert json keys to value, this question is being in MNCs

interview
Convert JSON key to values (vice-versa)

Input

var data = { first: 'John', last: 'Doe', email: 'john.doe@gmail.com' }   

Expected Output

{
 John : first,
 Doe : last,
 'john.doe@gmail.com' : email
}   

Solution

var data = { first: 'John', last: 'Doe', email: 'john.doe@gmail.com' };
var result = {};

for(var key in data)
{
    if(data.hasOwnProperty(key))
    {
        result[data[key]]=key
        
    }
}