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
.
So the expected output should be: 1, 3
, because the id 2 doesn't have any category id contained in teh references array.
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
.
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()
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.