Swap key with value in object
function swap(json){ var ret = {}; for(var key in json){ ret[json[key]] = key; } return ret;}
Example here FIDDLE don't forget to turn on your console to see the results.
ES6 versions:
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; }, {});}
you can use lodash function _.invert it also can use multivlaue
var object = { 'a': 1, 'b': 2, 'c': 1 }; _.invert(object); // => { '1': 'c', '2': 'b' } // with `multiValue` _.invert(object, true); // => { '1': ['a', 'c'], '2': ['b'] }
Using ES6:
const obj = { a: "aaa", b: "bbb", c: "ccc", d: "ddd" };Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a })))