Reverse la clave y el valor en el objeto JS
//The concise way by using ES6 syntax like this.
const obj = {A : 1, B : 2, C : 3, D : 4}
function objectFlip(obj) {
return Object.entries(obj).reduce((acc, [key, value]) => (acc[value] = key, acc), {})
}
console.log('input: ',obj);
console.log('output: ',objectFlip(obj));
static objectFlip(obj) {
const ret = {};
Object.keys(obj).forEach(key => {
ret[obj[key]] = key;
});
return ret;
}
//Or using Array.reduce() & Object.keys()
static objectFlip(obj) {
return Object.keys(obj).reduce((ret, key) => {
ret[obj[key]] = key;
return ret;
}, {});
}
//Or using Array.reduce() & Object.entries()
static objectFlip(obj) {
return Object.entries(obj).reduce((ret, entry) => {
const [ key, value ] = entry;
ret[ value ] = key;
return ret;
}, {});
}
abdelghanyMh