In: Computer Science
JavaScript Write a function named "reverse_kvs" that has a key-value store as a parameter and returns a new key-value store. Your function should add each key-value pair in the parameter to the new key-value store EXCEPT reversing the key and value. For example, if the key-value "extreme":45 were in the parameter then the returned key-value store should contain the key-value pair 45:"extreme". Code: function reverse_kvs(store) { var reverse_store = {}; for (var key in store) { if (store.hasOwnProperty(key)) { reverse_store[store[key]] = key; } } return reverse_store; }
I need to have this code return an output other than an empty result. Does anyone know how to fix the code?
*** UPDATE: The code is not correct. It returns an empty result, such as this "{}"***
Solution for the given question are as follows -
Note : I am using online java script compiler to run java script code. ( https://rextester.com/l/js_online_compiler )
Code:
function reverse_kvs(store) {
var reverse_store = {};
for (var key in store) {
if (store.hasOwnProperty(key)) {
reverse_store[store[key]] = key;
}
}
return reverse_store;
}
result = reverse_kvs({"name":"vikram"});
print("Result = " + JSON.stringify(result))
Code Screen Shot :
Output :