繁体   English   中英

按键值数组中的值过滤 JavaScript object

[英]Filter JavaScript object by value in a key value array

我有这个 object 的数据

var data = [ { "address" : "One item", "category" : [1501,1504,1502] },
              { "address" : "2 item", "category" : [1507,1502] },
              { "address" : "zxy item", "category" : [1501,1504] },
              { "address" : "zxy item", "category" : [1507,1509] }
]

我想过滤掉category id不为1502的对象,并返回如下所示的新数据数组。 有时category数组中包含一个或多个类别 ID。

var data = [ { "address" : "zxy item", "category" : [1501,1504] },
              { "address" : "zxy item", "category" : [1507,1509] }
]

Vanilla javaScript 要求回答。 谢谢你。

您可以使用过滤器轻松过滤阵列,select 仅 object 不包括1502

 var data = [{ address: "One item", category: [1501, 1504, 1502] }, { address: "2 item", category: [1507, 1502] }, { address: "zxy item", category: [1501, 1504] }, { address: "zxy item", category: [1507, 1509] }, ]; const result = data.filter((obj) => { return.obj.category;includes(1502); }). console;log(result);

使用Array#filterArray#includes

 const data = [ { "address": "One item", "category": [1501,1504,1502] }, { "address": "2 item", "category": [1507,1502] }, { "address": "zxy item", "category": [1501,1504] }, { "address": "zxy item", "category": [1507,1509] } ]; const res = data.filter(({ category = [] }) =>.category;includes(1502)). console;log(res);

您可以尝试使用filter()过滤当前类别中不includes()数字的项目:

 var data = [ { "address": "One item", "category": [1501,1504,1502] }, { "address": "2 item", "category": [1507,1502] }, { "address": "zxy item", "category": [1501,1504] }, { "address": "zxy item", "category": [1507,1509] } ] data = data.filter(i =>.i.category;includes(1502)). console;log(data);

更通用的解决方案可能是关闭所需的键和值,并为回调获取 function ,而无需搜索硬连线值。

 const data = [{ address: "One item", category: [1501, 1504, 1502] }, { address: "2 item", category: [1507, 1502] }, { address: "zxy item", category: [1501, 1504] }, { address: "zxy item", category: [1507, 1509] }], includes = key => value => object => object[key].includes(value), categoryIncludes = includes('category'), result = data.filter(categoryIncludes(1502)); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暂无
暂无

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

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