如何删除深层对象中的项目?

时间:2019-01-29 21:08:55

标签: javascript

假设我有以下对象数组:

[
   { 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"} ],
]

我要删除所有没有像category_id一样没有包含在此引用数组1, 4, 5中的项目。

因此,预期的输出应为:1, 3,因为id 2在引用数组中没有任何类别ID。

我写了这段代码:

items.filter(obj => !references.includes(obj.categories.category_id));

但这将返回相同的项目

预期结果:

[
   { id: "1", categories: [ { category_id: "1"}, { category_id: "2"} ],
   { id: "3", categories: [ { category_id: "1"}, { category_id: "5"} ],
]

3 个答案:

答案 0 :(得分:3)

您可以将Array#filterArray#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; }

答案 1 :(得分:1)

obj.categories是一个数组,您必须以某种方式对其进行迭代:

items.filter(obj => obj.categories.every(category => !references.includes(category.category_id)));

答案 2 :(得分:0)

这里您还有另一种使用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);