简体   繁体   English

如何从对象属性中的数组中过滤出项目

[英]How to filter out item from array in object property

I have an array of objects with this structure我有一个具有这种结构的对象数组

mockData: [{
    'ONE': [{
      id: 11,
      ...
    }, {
      id: 4,
      ...
    }]
  },
  {
    'TWO': [{
      id: 11,
      ...
    }]
  }
]

I want to filter out the item by id (for example with id === 11) and by Object key.我想通过 id(例如 id === 11)和 Object 键过滤掉项目。 For exmaple I want to delete例如我想删除

'ONE': [{
      id: 11,
      ...
    }

but leave the但离开

 {
    'TWO': [{
      id: 11,
      ...
    }]
  }

I figured out that filter just by id我只是通过 id 找出了那个过滤器

mockData.map(item => {
  return Object.values(item).map(inner => {
    return inner.filter(i => i.id !== id)
  });
})

This works but it removes the key of the object ('ONE', 'TWO' etc.) and returns data like this这有效,但它删除了对象的键('ONE'、'TWO' 等)并返回这样的数据

[[{id:3, ...}]],
[[]]

instead of代替

'TWO': []

All the help with adjusting my function to work properly will be much appreciated.将非常感谢调整我的功能以使其正常工作的所有帮助。

Also, I'm doing it in Redux reducer, so I can't mutate the initial array.另外,我是在 Redux reducer 中做的,所以我不能改变初始数组。

You can try using the Array.reduce method.您可以尝试使用Array.reduce方法。

Example:例子:

 const data = [ { ONE: [{ id: 11 }, { id: 12 }, { id: 13 }], TWO: [{ id: 11 }, { id: 12 }, { id: 13 }] } ]; const filtered = data.map(item => { return Object.keys(item).reduce((prev, key) => { prev[key] = item[key].filter(({ id }) => id !== 11); return prev; }, {}); }); console.log(filtered)

You need to separate the parts and get the most inner array along with the key and then add this result to the outer array.您需要将各个部分分开并获得最内部的数组以及键,然后将此结果添加到外部数组中。

 const filter = (array, id) => array.reduce((r, o) => { var hasContent, content = Object.assign({}, ...Object.entries(o).map(([k, v]) => { v = v.filter(o => o.id !== id); if (v.length) { hasContent = true; return { [k]: v }; } })); if (hasContent) r.push(content); return r; }, []); var data = { mockData: [{ ONE: [{ id: 11 }, { id: 4 }] }, { TWO: [{ id: 11 }] }] } console.log(filter(data.mockData, 11));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM