如何遍历json数据并合并具有相同状态ID的行?

时间:2018-12-03 18:47:22

标签: javascript jquery json jsobject

我有us-senat的.json文件,每个州都有两个参议员。我想遍历此json文件并创建一个新的JS对象,该对象应具有状态ID作为键,然后为每个键name1name2设置两个属性。这是数据在原始文件中的外观示例:

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>

在示例中,我仅显示了原始数据,这是我想要的:

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

在循环时,我将设置新键并使用值设置name1属性,如果键已经存在,则需要保留name1并使用新值设置第二个属性name2。我想知道这是否可行,最简单的方法是什么?

3 个答案:

答案 0 :(得分:2)

您是否正在寻找类似的东西?

senatorDataNew = {};    
senatorData.forEach(senator => {
    if (! senatorDataNew[senator.state_code]) {
        senatorDataNew[senator.state_code] = {names: []};
    }

    senatorDataNew[senator.state_code].names.push(senator.name)
});

答案 1 :(得分:2)

如果只有2位参议员,则可以使用reduce并根据是否存在密钥来在密钥旁边的对象中设置name1name2属性在累加器中:

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>

答案 2 :(得分:1)

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

//convert the object into an object of key (state) and value (names)
senatorData = senatorData.reduce(function(results, senator){
  if (!results[senator.state_code]) results[senator.state_code] = [];
  
  results[ senator.state_code ].push(senator.name);
  return results;
}, {});

console.log(senatorData);

//convert the object into an array of objects
senatorData = Object.keys(senatorData).map(function(state){
  return { state_code: state, names: senatorData[state] };
});

console.log(senatorData);