循环遍历集合会根据action属性将每个项目推送到新集合

时间:2015-05-07 17:00:28

标签: javascript loops

所以例如我有这个集合:

var items = [
{accntNumber: 12345, action: "Non Derogatory", bureau: "TU",      username: "pbutler"},
{accntNumber: 785, action: "Deleted", bureau: "EXP", username: "areston"},
{accntNumber: 956, action: "Deleted", bureau: "TU", username: "nikkim"},
{accntNumber: 1235, action: " 100% Non Derogatory", bureau: "TU", username: "ajaquez"},
{accntNumber: 45336, action: "Non Derogatory", bureau: "TU", username: "nikkim"},
{accntNumber: 845, action: "Newly Negative", bureau: "TU", username: "areston"},
{accntNumber: 9875, action: "No Longer On Report", bureau: "TU", username: "ajaquez"}
]

我想循环遍历它并找到“action”键并将整个对象推送到相应的数组: 因此,对于示例,已删除的项应该放在已删除的数组中,非Derogatory项应该全部放在nonDerogatoryItems数组中。

var nonDerogatoryItems = [];
var deleted = [];
var _100nonDerogatoryItems = [];
var newlyNegative = [];
var noLongerOnReport = [];

2 个答案:

答案 0 :(得分:1)

如果希望使用任何库,只有一种非常简单的方法可以使用纯JavaScript 来完成您想要的内容:

// Assuming you already declared 'items' with it's objects
var nonDerogatoryItems = deleted = _100nonDerogatoryItems = newlyNegative = noLongerOnReport = undefinedActionArray = [];

for(var i in items){
  switch(items[i].action){
    case 'Deleted':
      deleted.push(items[i]);
      break;
    case 'Newly Negative':
      newlyNegative.push(items[i]);
      break;

    // [...] and so on for the other possible actions

    // In case any action goes missing (doesn't match the switch), you can debug this and check 
    // what happened, if there was any mistype or so
    default:
      undefinedActionArray.push(items[i]);
      break;
  }
}

现在,如果您正在寻找使用更少线条但更复杂的工作,那么您可以这样做:

var actions = [];
for(var i in items){

    // If this action wasn't set yet
    if(typeof actions[items[i].action] === 'undefined')
      actions[items[i].action] = []; // Starts as an empty array

    // Now pushes the current item into it's group
    actions[items[i].action].push(items[i]);

}

最终会产生这样的结果:

actions = [
  "Deleted" = [
    {accntNumber: 785, action: "Deleted", bureau: "EXP", username: "areston"},
    {accntNumber: 956, action: "Deleted", bureau: "TU", username: "nikkim"}
  ],
  "Non Derogatory" = [
    {accntNumber: 12345, action: "Non Derogatory", bureau: "TU",      username: "pbutler"},
    {accntNumber: 45336, action: "Non Derogatory", bureau: "TU", username: "nikkim"}
  ],
  // [...] And so forth
]

底线

第一个示例更简单,但根据存在的actions的数量,您将拥有一个大脚本。此外,每当出现新的action类型时,您都需要更新代码。

第二个示例更具动态性并适应变化。只需几行,您就可以计算actions个对象中可能存在的所有items

答案 1 :(得分:0)

只需使用您最喜欢的功能库。

groupedItems = _.groupBy(items, 'action')

groupedItems.Deleted.length // 2

这个很好https://lodash.com/docs#groupBy