Swap key with value JSON

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

    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"]
    

提交回复
热议问题