Swap key with value JSON

瘦欲@ 提交于 2019-11-27 11:44:53
jPO
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 version:

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

Get the keys of the object, and then use the Array's reduce function to go through each key and set the value as the key, and the key as the value.

var data = {A : 1, B : 2, C : 3, D : 4}
var newData = Object.keys(data).reduce(function(obj,key){
   obj[ data[key] ] = key;
   return obj;
},{});
console.log(newData);
Ohad Sadan

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'] }

In ES6/ES2015 you can combine use of Object.keys and reduce with the new Object.assign function, an arrow function, and a computed property name for a pretty straightforward single statement solution.

const foo = { a: 1, b: 2, c: 3 };
const bar = Object.keys(foo)
    .reduce((obj, key) => Object.assign({}, obj, { [foo[key]]: key }), {});

If you're transpiling using the object spread operator (stage 3 as of writing this) that will simplify things a bit further.

const foo = { a: 1, b: 2, c: 3 };
const bar = Object.keys(foo)
    .reduce((obj, key) => ({ ...obj, [foo[key]]: key }), {});

Finally, if you have Object.entries available (stage 4 as of writing), you can clean up the logic a touch more (IMO).

const foo = { a: 1, b: 2, c: 3 };
const bar = Object.entries(foo)
    .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {});

Using ES6:

const obj = { a: "aaa", b: "bbb", c: "ccc", d: "ddd" };
Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a })))

As a complement of @joslarson and @jPO answers:
Without ES6 needed, you can use Object.keys Array.reduce and the Comma Operator:

Object.keys(foo).reduce((obj, key) => (obj[foo[key]] = key, obj), {});

Some may find it ugly, but it's "kinda" quicker as the reduce doesn't spread all the properties of the obj on each loop.

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

Using Ramda:

const swapKeysWithValues = 
  R.pipe(
    R.keys,
    R.reduce((obj, k) => R.assoc(source[k], k, obj), {})
  );

const result = swapKeysWithValues(source);

Try

let swap = (o,r={})=> Object.keys(o).map(x=>r[o[x]]=x)&&r;

let obj = {A : 1, B : 2, C : 3, D : 4};

let swap = (o,r={})=> Object.keys(o).map(x=>r[o[x]]=x)&&r;

console.log(swap(obj));

I believe it's better to do this task by using an npm module, like invert-kv.

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

https://www.npmjs.com/package/invert-kv

const invertKv = require('invert-kv');

invertKv({foo: 'bar', unicorn: 'rainbow'});
//=> {bar: 'foo', rainbow: 'unicorn'}

With pure Ramda in a pure and point-free style:

const swapKeysAndValues = R.pipe(
   R.toPairs,
   R.map(R.reverse),
   R.fromPairs,
);

Or, with a little more convoluted ES6 version, still pure functional:

const swapKeysAndValues2 = obj => Object
    .entries(obj)
    .reduce((newObj, [key, value]) => ({...newObj, [value]: key}), {})
    var data = {A : 1, B : 2, C : 3, D : 4}
    var newData = {};
    Object.keys(data).forEach(function(key){newData[data[key]]=key});
    console.log(newData);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!