Swap key with value JSON

后端 未结 18 2377
花落未央
花落未央 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:05

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

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

    Or using Array.reduce() & Object.keys()

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

    Or using Array.reduce() & Object.entries()

    static objectFlip(obj) {
      return Object.entries(obj).reduce((ret, entry) => {
        const [ key, value ] = entry;
        ret[ value ] = key;
        return ret;
      }, {});
    }
    
    0 讨论(0)
  • 2020-11-30 00:09

    Here is a pure functional implementation of flipping keys and values in ES6:

    TypeScript

      const flipKeyValues = (originalObj: {[key: string]: string}): {[key: string]: string} => {
        if(typeof originalObj === "object" && originalObj !== null ) {
          return Object
          .entries(originalObj)
          .reduce((
            acc: {[key: string]: string}, 
            [key, value]: [string, string],
          ) => {
            acc[value] = key
            return acc;
          }, {})
        } else {
          return {};
        }
      }
    

    JavaScript

    const flipKeyValues = (originalObj) => {
        if(typeof originalObj === "object" && originalObj !== null ) {
            return Object
            .entries(originalObj)
            .reduce((acc, [key, value]) => {
              acc[value] = key
              return acc;
            }, {})
        } else {
            return {};
        }
    }
    
    const obj = {foo: 'bar'}
    console.log("ORIGINAL: ", obj)
    console.log("FLIPPED: ", flipKeyValues(obj))

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

    Here is an option that will swap keys with values but not lose duplicates, if your object is : { a: 1, b: 2, c: 2}, it will always return an array in the output :

    function swapMap(map) {
        const invertedMap = {};
        for (const key in map) {
            const value = map[key];
            invertedMap[value] = invertedMap[value] || [];
            invertedMap[value].push(key);
        }
        return invertedMap;
    }
    swapMap({a: "1", b: "2", c: "2"})
    // Returns => {"1": ["a"], "2":["b", "c"]}
    
    0 讨论(0)
  • 2020-11-30 00:11
        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);
    
    0 讨论(0)
  • 2020-11-30 00:11
    function swapKV(obj) {
      const entrySet = Object.entries(obj);
      const reversed = entrySet.map(([k, v])=>[v, k]);
      const result = Object.fromEntries(reversed);
      return result;
    }
    

    This can make your object, {A : 1, B : 2, C : 3, D : 4}, array-like, so you can have

    const o = {A : 1, B : 2, C : 3, D : 4}
    const arrayLike = swapKV(o);
    arrayLike.length = 5;
    const array = Array.from(arrayLike);
    array.shift(); // undefined
    array; // ["A", "B", "C", "D"]
    
    0 讨论(0)
提交回复
热议问题