//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;
}, {});
}
var object = { 'a': 1, 'b': 2, 'c': 1 };
//This uses the package lodash
_.invert(object);
// => { '1': 'c', '2': 'b' }
// with `multiValue`
_.invert(object, true);
// => { '1': ['a', 'c'], '2': ['b'] }