Swap key with value JSON

后端 未结 18 2351
花落未央
花落未央 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-30 00:11

    Rewriting answer of @Vaidd4, but using Object.assign (instead of comma operator):

    /**
     * Swap object keys and values
     * @param {Object<*>} obj
     * @returns {Object<string>}
     */
    function swapObject(obj) {
        return Object.keys(obj).reduce((r, key) => (Object.assign(r, {
            [obj[key]]: key,
        })), {});
    }
    

    Or, shorter:

    Object.keys(obj).reduce((r, key) => (Object.assign(r, {[obj[key]]: key})), {});
    
    0 讨论(0)
  • 2020-11-30 00:12

    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.

    0 讨论(0)
  • 2020-11-30 00:13

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

    0 讨论(0)
  • 2020-11-30 00:13

    Shortest one I came up with using ES6..

    const original = {
     first: 1,
     second: 2,
     third: 3,
     fourth: 4,
    };
    
    
    const modified = Object
      .entries(original)
      .reduce((all, [key, value]) => ({ ...all, [value]: key }), {});
    
    console.log('modified result:', modified);

    0 讨论(0)
  • 2020-11-30 00:20

    A simple TypeScript variant:

    const reverseMap = (map: { [key: string]: string }) => {
        return Object.keys(map).reduce((prev, key) => {
            const value = map[key];
            return { ...prev, [value]: [...(prev.value || []), key] };
        }, {} as { [key: string]: [string] })
    }
    

    Usage:

    const map = { "a":"1", "b":"2", "c":"2" };
    const reversedMap = reverseMap(map);
    console.log(reversedMap);
    

    Prints: { "1":["a"], "2":["b", "c"] }

    0 讨论(0)
  • 2020-11-30 00:21

    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'] }
    
    0 讨论(0)
提交回复
热议问题