如何根据数组中对象的某个属性值生成对应的多个数组

今天有个朋友问了我一个需求,她有个数组,需要根据数组中的type字段生成对应type相同的数组,而这个type是前端界面上动态添加获得的,也不曾有码表。

先上数组

var arr = [
    {regulationsId: 5172, title: "测试111标题2 ", type: 610, state: 1, createdTime: 1530152467000},
    {regulationsId: 5169, title: "测试111标题", type: 610, state: 1, createdTime: 1530085573000},
    {regulationsId: 5170, title: "测试123标题", type: 609, state: 1, createdTime: 1530085687000},
    {regulationsId: 5171, title: "测试1122标题", type: 608, state: 1, createdTime: 1530085750000}
];

可以发现这个需求就是数组的名称要动态生成,奉上代码如下:

var arr = [
    {regulationsId: 5172, title: "测试111标题2 ", type: 610, state: 1, createdTime: 1530152467000},
    {regulationsId: 5169, title: "测试111标题", type: 610, state: 1, createdTime: 1530085573000},
    {regulationsId: 5170, title: "测试123标题", type: 609, state: 1, createdTime: 1530085687000},
    {regulationsId: 5171, title: "测试1122标题", type: 608, state: 1, createdTime: 1530085750000}
];

//先获取一下这个数组中有多少个type
var types = [];
for(var i in arr){
    if(types.indexOf(arr[i].type) === -1){
        types.push(arr[i].type)
    }
}
//一个包含多个list的结果对象
var obj = {};

// 根据type生成多个数组
for(var k in types){
    for(var j in arr){
        if(arr[j].type == types[k]){
            console.log(types[k], ">>>>>>>>>", arr[j])
            obj[types[k]] = obj[types[k]] || [];
            obj[types[k]].push(arr[j])
        }
    }
}
console.log(types)
console.log(obj)

解决方案如上,应该还有高逼格的实现方法,本人愚钝,暂时想到这个方法。

 

转载于:https://www.cnblogs.com/zyl-Tara/p/9243873.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值