Swap key with value JSON

后端 未结 18 2507
花落未央
花落未央 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: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"] }

提交回复
热议问题