[英]Filter JavaScript object by value in a key value array
I have this object of data我有这个 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] }
]
I would like to filter out the objects that do not have the category id
of 1502
and return the new data array like this below.我想过滤掉
category id
不为1502
的对象,并返回如下所示的新数据数组。 Sometimes the category
array has one or more category ids in it.有时
category
数组中包含一个或多个类别 ID。
var data = [ { "address" : "zxy item", "category" : [1501,1504] },
{ "address" : "zxy item", "category" : [1507,1509] }
]
Vanilla javaScript answers requested. Vanilla javaScript 要求回答。 Thank you.
谢谢你。
You can easily filter the array using filter and select only the object that doesnot includes the 1502
您可以使用过滤器轻松过滤阵列,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);
Using Array#filter
and Array#includes
:使用
Array#filter
和Array#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);
You can try using filter()
to filter the items that does not includes()
the number in the current category:您可以尝试使用
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);
A more versatile solution could be a closure over the wanted key and the value and get a function for the callback without having a hard wired value to search.更通用的解决方案可能是关闭所需的键和值,并为回调获取 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.