Swap key with value JSON

2019-01-11 00:11发布

I have an extremely large JSON object structured like this:

{A : 1, B : 2, C : 3, D : 4}

I need a function that can swap the values with keys in my object and I don't know how to do it. I would need an output like this:

{1 : A, 2 : B, 3 : C, 4 : D}

Is there any way that I can do this would manually created a new object where everything is swapped?
Thanks

7条回答
祖国的老花朵
2楼-- · 2019-01-11 00:37

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);
查看更多
beautiful°
3楼-- · 2019-01-11 00:41
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.

查看更多
Animai°情兽
4楼-- · 2019-01-11 00:41

Using ES6:

const obj = { a: "aaa", b: "bbb", c: "ccc", d: "ffffd" };
Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a })))
查看更多
ら.Afraid
5楼-- · 2019-01-11 00:43

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'] }
查看更多
干净又极端
6楼-- · 2019-01-11 00:47

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 }), {});
查看更多
不美不萌又怎样
7楼-- · 2019-01-11 00:47

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.

查看更多
登录 后发表回答