使用Lodash从嵌套对象中删除属性

时间:2019-03-04 00:10:05

标签: lodash

嗨,我有以下对象:

{ "name": "Joe", "email": "joe.smith@test.com", "items": [ { "id": "1", "name": "Name 1" }, { "id": "2", "name": "Name 2" }...] }

我需要从所有“项目”中删除name属性,我尝试使用omit,但似乎无法正常工作:

_.omit(this.user, ["items.name"]);

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

_.omit()方法不能以这种方式用于多个项目。您可以将_.map()_.omit()一起使用:

const user = { "name": "Joe", "email": "joe.smith@test.com", "items": [ { "id": "1", "name": "Name 1" }, { "id": "2", "name": "Name 2" }] }

const result = {
  ...user,
  items: _.map(user.items, user => _.omit(user, 'name'))
}

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>