javascriptjqueryjsonjsobject

How to loop over json data and merge rows with the same state id?


I have .json file of us-senat that has two senators for each state. I would like to loop over this json file and create new JS object that should have state id as a key and then set two properties for each key name1 and name2. Here is example of how data looks in original file:

var senatorData = [{
    state_code: "AK",
    name: "Daniel Sullivan"
  },
  {
    state_code: "AK",
    name: "Lisa Murkowski"
  },
  {
    state_code: "WY",
    name: "Michael Enzi"
  },
  {
    state_code: "WY",
    name: "John Barrasso"
  }
];

$(document).ready(function(){
  loadData();
});

function loadData() {
  if (senatorData) {
    for (var key in senatorData) {
      console.log(senatorData[key]);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In example I just showed the original data, here is what I would like to have:

var senatorDataNew = [
    "AK" = {
         name1: "Daniel Sullivan",
         name2: "Lisa Murkowski"
     },
     "WY" = {
         name1: "Michael Enzi",
         name2: "John Barrasso"
     }
];

While looping I would set new key and set the name1 property with value, if key already exists I need to keep name1 and set second property name2 with new value. I'm wondering if this is possible and what is the easiest way to achieve that?


Solution

  • If there are only 2 senators, you can use reduce and set the name1 or name2 property in the object next to the key based on whether or not a key is already present in the accumulator:

    function loadData() {
      if (senatorData) {
        return senatorData.reduce((a, {state_code, name}) => {
          if (state_code in a) a[state_code].name2 = name;
          else a[state_code] = {name1: name};
          return a;
        }, {});
      }
    }
    
    var senatorData = [{
        state_code: "AK",
        name: "Daniel Sullivan"
      },
      {
        state_code: "AK",
        name: "Lisa Murkowski"
      },
      {
        state_code: "WY",
        name: "Michael Enzi"
      },
      {
        state_code: "WY",
        name: "John Barrasso"
      }
    ];
    
    $(document).ready(function(){
      console.log(loadData());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>