按属性组合对象数组

时间:2017-12-03 00:39:51

标签: javascript lodash

嗨那里,我正在尝试组合一个对象数组,并且需要最终结果是一个对象数组,其中一个attr唯一,另一个是一个数组,其中包含来自原始第二个attr的所有值

我有的数组:

let arr = [
    { 
        name: 'cdd_register', 
        levels: 'read' 
    }, { 
        name: 'cdd_register', 
        levels: 'write' 
    }, { 
        name: 'annual_reports', 
        levels: 'write' 
    }
];

我期望的结果是:

let result = [
    { 
        name: 'cdd_register', 
        levels: ['read', 'write']
    }, { 
        name: 'annual_reports', 
        levels: 'write' 
    }
];

我从后端得到了这个回复

data: [{
    id:1
    label: "Administrator"
    name: "admin"
    permissions:{
        data: [{
            id: 4, 
            name: "cdd_register.read", 
            label: "Read access on CDD Register module"
        }, {
            id: 6, 
            name: "cdd_register.write", 
            label: "Write access on CDD Register module"
        }, {
            id: 7, 
            name: "annual_reports.write", 
            label: "Write access on Annual Reports module"
        }]
    }
}]

此后

getModules(roles) {
    let modules = [];

    _.forEach(roles, role => {
        _.forEach(role.permissions.data, permission => {
            modules.push(permission);
        })
    });

    return _.uniqBy(modules, 'id').map(module => {
        let moduleArray = module.name.split('.');
            return {
                 name: moduleArray[0],
                 levels: moduleArray[1]
            }
        });
    }
}

我现在有结果,但无法找出最佳方法(干净)。

感谢。

1 个答案:

答案 0 :(得分:0)

这可以通过许多不同的方式完成。一种可能的方法是使用一些功能魔法

let arr = [{
  name: 'cdd_register',
  levels: 'read'
}, {
  name: 'cdd_register',
  levels: 'write'
}, {
  name: 'annual_reports',
  levels: 'write'
}];

let result = arr.reduce((acc, x) => {
  const found = acc.find(y => (x.name == y.name));
  if (!found) {
    acc.push({
      name: x.name,
      levels: arr
        .filter(y => (x.name == y.name))
        .map(z => (z.levels))
    });
  }
  return acc;
}, [])

console.log(result)