Swap key with value JSON

后端 未结 18 2350
花落未央
花落未央 2020-11-29 23:54

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

相关标签:
18条回答
  • 2020-11-29 23:55

    Using ES6:

    const obj = { a: "aaa", b: "bbb", c: "ccc", d: "ffffd" };
    Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a })))
    
    0 讨论(0)
  • 2020-11-29 23:56

    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'}
    
    0 讨论(0)
  • 2020-11-29 23:58

    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)

    0 讨论(0)
  • 2020-11-29 23:59

    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 }), {});
    
    0 讨论(0)
  • 2020-11-30 00:02

    Using Ramda:

    const swapKeysWithValues = 
      R.pipe(
        R.keys,
        R.reduce((obj, k) => R.assoc(source[k], k, obj), {})
      );
    
    const result = swapKeysWithValues(source);
    
    0 讨论(0)
  • 2020-11-30 00:03

    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.

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

    0 讨论(0)
提交回复
热议问题