Lodash:根据条件查找和删除多级Json中的项目?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (644)

我试图根据条件删除“角色数组”中的项目,但此数组是json数组中的项目。此外,我必须在查看roles数组之前在父级别再检查一个条件。我厌倦了lodash的发现,首先匹配父级别的第一个条件,但无法继续进行下一级别的过滤。

我的json:

[ {"unitId": "2", name: "elizabeth", roles: [{ "role":{"roleId" : "2", roleName: "testing"}},  { "role":{"roleId" : "5", roleName: "dev"}}]},
{"unitId": "2", name: "peter", roles: [{ "role":{"roleId" : "1", roleName: "testing"}},  { "role":{"roleId" : "2", roleName: "dev"}}]}
]

预期结果:

[ {"unitId": "2", name: "elizabeth", roles: [{ "role":{"roleId" : "2", roleName: "testing"}}}]},
{"unitId": "2", name: "peter", roles: [{ "role":{"roleId" : "1", roleName: "testing"}},  { "role":{"roleId" : "2", roleName: "dev"}}]}
]

这里我需要首先检查unitId:2,然后在该unitId中删除roleId:5的所有角色:2

提问于
用户回答回答于

您可以使用mapremove与lodash:

const data = [{ unitId: "2", name: "elizabeth", roles: [{ "role": { "roleId": "2", roleName: "testing" } }, { "role": { "roleId": "5", roleName: "dev" } }] }, { unitId: "2", name: "peter", roles: [{ "role": { "roleId": "1", roleName: "testing" } }, { "role": { "roleId": "2", roleName: "dev" } }] } ]

const result = _.map(data, x => (_.isEqual(x.unitId, "2") ? 
   _.remove(x.roles, y => y.role.roleId == "5") : null, x))

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

你也可以跳过lodash并做:

const data = [{ unitId: "2", name: "elizabeth", roles: [{ "role": { "roleId": "2", roleName: "testing" } }, { "role": { "roleId": "5", roleName: "dev" } }] }, { unitId: "2", name: "peter", roles: [{ "role": { "roleId": "1", roleName: "testing" } }, { "role": { "roleId": "2", roleName: "dev" } }] } ]

const result = data.map(x => (x.roles = x.unitId == "2" ? 
  x.roles.filter(y => y.role.roleId != '5') : x.roles, x))

console.log(result)

使用mapfilter

扫码关注云+社区

领取腾讯云代金券