如何在JavaScript中对一些常见属性进行分组?

时间:2017-05-22 14:02:45

标签: javascript

以下是我在一些操作后的回复。根据empid我想分区,产品并获得短信和whatsapp的数量。

[
  {
    "_id": {
      "empid": "sindhu",
      "district": "Hyderabad",
      "product": "Fair Fertilizers"
    },
    "sms": 1
  },
  {
    "_id": {
      "empid": "nagaraju",
      "district": "Guntur",
      "product": "Fair Fertilizers"
    },
    "sms": 2
  },
  {
    "_id": {
      "empid": "sindhu",
      "district": "Hyderabad",
      "product": "Fair Fertilizers"
    },
    "whatsapp": 2
  },
  {
    "_id": {
      "empid": "sindhu",
      "district": "Krishna",
      "product": "Fair Fertilizers"
    },
   "whatsapp": 2
  }
]

我想要的格式如下所示。

[
  {
    "sindhu":[
        {
          "district": "Hyderabad",
          "product": "Fair Fertilizers",
          "sms": 1,
          "whatsapp": 2
        },
        {
          "district": "Krishna",
          "product": "Fair Fertilizers",
          "whatsapp": 2
        },
    ]
  },
  {
    "nagaraju" : [
        {
          "district": "Guntur",
          "product": "Fair Fertilizers",
          "sms": 2
        }
     ]
  }
]

为了得到这样,我尝试了下面的代码。但我没有得到它。

var groups = Object.create(null);
for (var i = 0; i < allTools.length; i++) {
    var item = allTools[i];
    if(!groups[item._id]) {
        groups[item._id] = [];
    }
    groups[item._id].push({
        district: item.district,
        product: item.product,
        sms: item.sms,
        whatsapp: item.whatsapp,
        mailing: item.mailing,
        telecalling: item.telecalling,
        enquiry: item.enquiry
    });
}
var data = [];
for (var x in groups) {
    var obj = {};
    obj[x] = groups[x];
    data.push(obj);
}

1 个答案:

答案 0 :(得分:1)

您可以使用迭代嵌套方法,通过使用哈希表来构建对结果数组的必要引用,该哈希表适用于使用键以及保留部分结果。

由于empiddistrict的每个级别的分组键的需求不同,因此无法实现更大的简化。

var data = [{ _id: { empid: "sindhu", district: "Hyderabad", product: "Fair Fertilizers" }, sms: 1 }, { _id: { empid: "nagaraju", district: "Guntur", product: "Fair Fertilizers" }, sms: 2 }, { _id: { empid: "sindhu", district: "Hyderabad", product: "Fair Fertilizers" }, whatsapp: 2 }, { _id: { empid: "sindhu", district: "Krishna", product: "Fair Fertilizers" }, whatsapp: 2 }],
    values = ['sms', 'whatsapp'],
    result = [],
    hash = { _: result };

data.forEach(function (o) {
    var temp = {},
        reference = hash;

    if (!reference[o._id.empid]) {
        reference[o._id.empid] = { _: [] };
        temp[o._id.empid] = reference[o._id.empid]._;
        reference._.push(temp);
    }
    reference = reference[o._id.empid];

    if (!reference[o._id.district]) {
        reference[o._id.district] = { district: o._id.district, product: o._id.product };
        reference._.push(reference[o._id.district]);
    }
    reference = reference[o._id.district];

    values.forEach(function (k) {
        if (k in o) {
            reference[k] = o[k];
        }
    });
});

console.log(result);
console.log(hash);
.as-console-wrapper { max-height: 100% !important; top: 0; }