[英]How to remove items in deep array of objects?
Suppose I have the following array of objects: 假设我有以下对象数组:
[
{ id: "1", categories: [ { category_id: "1"}, { category_id: "2"} ],
{ id: "2", categories: [ { category_id: "2"}, { category_id: "3"} ],
{ id: "3", categories: [ { category_id: "1"}, { category_id: "5"} ],
]
I want remove all the items which doesn't have as category_id
those not included in this array of references: 1, 4, 5
. 我要删除所有没有作为
category_id
的项目,这些项目不包括在此引用数组中: 1, 4, 5
。
So the expected output should be: 1, 3
, because the id 2 doesn't have any category id contained in teh references array. 因此,预期的输出应为:
1, 3
,因为id 2在reference数组中没有任何类别id。
I wrote this code: 我写了这段代码:
items.filter(obj => !references.includes(obj.categories.category_id));
but this will return the same items 但这将返回相同的项目
Expected result: 预期结果:
[
{ id: "1", categories: [ { category_id: "1"}, { category_id: "2"} ],
{ id: "3", categories: [ { category_id: "1"}, { category_id: "5"} ],
]
You could use Array#filter
, Array#some
and the value with Array#includes
. 您可以使用
Array#filter
, Array#some
和带有Array#includes
的值。
var array = [{ id: "1", categories: [{ category_id: "1" }, { category_id: "2" }] }, { id: "2", categories: [{ category_id: "2" }, { category_id: "3" }] }, { id: "3", categories: [{ category_id: "1" }, { category_id: "5" }] }], keep = ["1", "4", "5"], result = array.filter(({ categories }) => categories.some(({ category_id }) => keep.includes(category_id))); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
obj.categories
是一个数组,您必须以某种方式对其进行迭代:
items.filter(obj => obj.categories.every(category => !references.includes(category.category_id)));
Here you have another approach that uses Array::findIndex() 在这里,您还有另一种使用Array :: findIndex()的方法
const input = [ {id: "1", categories: [{category_id: "1"}, {category_id: "2"}]}, {id: "2", categories: [{category_id: "2"}, {category_id: "3"}]}, {id: "3", categories: [{category_id: "1"}, {category_id: "5"}]}, ]; const references = [1, 4, 5]; let res = input.filter( y => y.categories.findIndex(x => references.includes(Number(x.category_id))) >= 0 ); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.