简体   繁体   English

如何在目标数组值内匹配javascript源数组键

[英]How to match javascript source array keys within target array values

I have two arrays in javascript(Jquery 3.2). 我在javascript(Jquery 3.2)中有两个数组。 One array (source) has key-value pairs and other(target) has values only. 一个数组(源)具有键值对,而另一个(目标)仅具有值。 I want to return those key-values from source which has matching values in other(target) array. 我想从其他(目标)数组中具有匹配值的源返回那些键值。 Here are the arrays. 这是数组。

var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}];
var target = ["a", "b", "c","d"];

You can filter the source base on the target by checking the first key in each source item. 您可以通过检查每个源项目中的第一个键来基于目标过滤源。 But this assumes the source items will only have one key. 但这假设源项目只有一个密钥。 This will fail if there are items like {a: 3, d:4} . 如果存在{a: 3, d:4}类的项目,则此操作将失败。

 var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 }, {"k":12}]; var target = ["a", "b", "c","d"]; let filtered = source.filter(item => target.includes(Object.keys(item)[0])) console.log(filtered) 

 var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}]; var target = ["a", "b", "c","d"]; console.log( //filter the sources on the target values source.filter(function(element){ //should show the element, if the key is in the target list return target.indexOf(Object.keys(element)[0]) > -1; }) ); 

There are different was to do this.One of them using filter is as below: 这样做是有区别的,其中一个使用filter的方法如下:

 var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}]; var target = ["a", "b", "c","d"]; var filteredArray = source.filter(function(array_el){ return target.filter(function(target_el){ return target_el == Object.keys(array_el); }).length > 0 }); console.log(filteredArray); 

One option is to use set on target, this will make it easier to check if the set has a certain element. 一种选择是在目标上使用set ,这将使检查set has具有特定元素变得更加容易。 Use filter to filter the source array. 使用filter过滤source数组。

 var source = [{ "a": 3 }, { "b": 2 }, { "c": 1 },{"k":12}]; var target = ["a", "b", "c", "d"]; var tempSet = new Set(target); var result = source.filter(o => tempSet.has(Object.keys(o)[0])); console.log(result); 

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

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