我正在尝试过滤 JSON 对象 orig
,如下所示。
orig = [
{model: 'model1', fields :{target:[1, 2], another_field:"random1"}},
{model: 'model2', fields :{target:[1, 3, 4], another_field:"random2"}},
{model: 'model3', fields :{target:[2, 5], another_field:"random3"}}
]
我希望能够使用过滤器 target_filter = 1
检索 orig
中目标数组包含 1 的每个项目。因此预期输出为:
filtered = [
{model: 'model1', fields :{target:[1, 2], another_field:"random1"}},
{model: 'model2', fields :{target:[1, 3, 4], another_field:"random2"}},
]
我查过this answer但我不确定如果子数组更深,如何使其工作。非常感谢您的帮助!
最佳答案
您可以找到正确的属性并通过 Array#includes
进行检查。 .
var array = [{ model: 'model1', fields: { target: [1, 2], another_field: "random1" } }, { model: 'model2', fields: { target: [1, 3, 4], another_field: "random2" } }, { model: 'model3', fields: { target: [2, 5], another_field: "random3" } }],
target_filter = 1,
result = array.filter(({ fields: { target } }) => target.includes(target_filter));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
没有 destructuring assignment ,你可能会使用
array.filter(object => object.fields.target.includes(target_filter))
关于如果子数组包含项目,Javascript 将过滤 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163795/