Swap key with value JSON

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

    Get the keys of the object, and then use the Array's reduce function to go through each key and set the value as the key, and the key as the value.

    const data = {
      A: 1,
      B: 2,
      C: 3,
      D: 4
    }
    const newData = Object.keys(data).reduce(function(obj, key) {
      obj[data[key]] = key;
      return obj;
    }, {});
    console.log(newData);

提交回复
热议问题