Swap a list of JSON key with value

You have this


	let player_icon = {
	  boss: "b",
	  earth: ".",
	  enemy: "e",
	  floor: "f",
	  health: "h",
	  player: "p",
	  wall: "w",
	  weapon: "w"
	}

But need this


	let icon_linked_to_player = {
	  .: "earth",
	  b: "boss",
	  e: "enemy",
	  f: "floor",
	  h: "health",
	  p: "player",
	  w: "weapon"
	}

We can write a function to do this. It comes in handy, especially when you have a long list of objects.


	let icon_linked_to_player =
	  Object.keys(player_icon).reduce(function(obj, key) {
	    obj[player_icon[key]] = key;
	    return obj;
	  }, {});

Invert the key/value of an object. Example: {foo: 'bar'} → {bar: 'foo'}

The Object.keys() method is used to return all the keys of the object. On this array of keys, the respective key is returned. This is the key to the value of the object.


The Object.fromEntries() method takes a list of key-value pairs and returns a new object whose properties are given by those entries.

The Object.fromEntries() method transforms a list of key-value pairs into an object.


	function swap(json){
		var ret = {};
		for(var key in json){
			ret[json[key]] = key;
		}
		return ret;
	}

ES6 version:


	static objectFlip(obj) {
		const ret = {};
		Object.keys(obj).forEach(key => {
			ret[obj[key]] = key;
		});
		return ret;
	}

Object.fromEntries version:


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

	console.log(
	f({A : 'a', B : 'b', C : 'c'})
	)
	// => {a : 'A', b : 'B', c : 'C'}

lodash function _.invert version:


	var object = { 'a': 1, 'b': 2, 'c': 1 };

	_.invert(object);
	// => { '1': 'c', '2': 'b' }

	// with `multiValue`
	_.invert(object, true);
	// => { '1': ['a', 'c'], '2': ['b'] }

CodersTool Categories