基于另一个数组动态筛选数组



我是JS的新手。我想在其他数组的基础上对数组应用过滤器。例如:根据colNames中的属性名称和Values数组中的值筛选data数组。colNamesValues阵列可以具有任何长度(不总是2(。

var data = [{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "320800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"rating": "5421"
},
{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "170750",
"start_date": "2011/07/25",
"office": "Tokyo",
"rating": "8422"
},
{
"name": "Garrett Winters",
"position": "Analyst",
"salary": "170750",
"start_date": "2011/07/25",
"office": "Tokyo",
"rating": "8422"
},
{
"name": "Ashton Cox",
"position": "Junior Technical Author",
"salary": "86000",
"start_date": "2009/01/12",
"office": "San Francisco",
"rating": "1562"
},
{
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "433060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"rating": "6224"
}
]

var colNames = ['name', 'position']
var Values = ['Garrett Winters', 'Accountant']

预期结果

[{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "170750",
"start_date": "2011/07/25",
"office": "Tokyo",
"rating": "8422"
}]

您可以使用所有键的迭代进行筛选并使用值进行检查。

const
data = [{ name: "Tiger Nixon", position: "System Architect", salary: "320800", start_date: "2011\/04\/25", office: "Edinburgh", rating: "5421" }, { name: "Garrett Winters", position: "Accountant", salary: "170750", start_date: "2011\/07\/25", office: "Tokyo", rating: "8422" }, { name: "Garrett Winters", position: "Analyst", salary: "170750", start_date: "2011\/07\/25", office: "Tokyo", rating: "8422" }, { name: "Ashton Cox", position: "Junior Technical Author", salary: "86000", start_date: "2009\/01\/12", office: "San Francisco", rating: "1562" }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: "433060", start_date: "2012\/03\/29", office: "Edinburgh", rating: "6224" }],
cols = ['name', 'position'],
values = ['Garrett Winters', 'Accountant'],
result = data.filter(o => cols.every((k, i) => o[k] === values[i]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新