Swap key with value JSON

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

提交回复
热议问题