Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap key with value in object

People also ask

How do you reverse the key and value of an object?

invert() method of “underscore. js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys.

How do you swap objects in JavaScript?

You can swap any number of objects or literals, even of different types, using a simple identity function like this: var swap = function (x){return x}; b = swap(a, a=b); c = swap(a, a=b, b=c); This works in JavaScript because it accepts additional arguments even if they are not declared or used.


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 })))

Now that we have Object.fromEntries:

obj => Object.fromEntries(Object.entries(obj).map(a => a.reverse()))

or

obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]))

(Updated to remove superfluous parentheses - thanks @devin-g-rhode)