Swap key with value JSON

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

提交回复
热议问题