I have two arrays in 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"];
I have two arrays in 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"];
Share
Improve this question
asked Jul 27, 2018 at 15:37
capnamcapnam
4379 silver badges26 bronze badges
2
-
So what is your expected output?
[{ "a": 3 }, { "b": 2 }, { "c": 1 }]
perhaps? Also, what have you tried so far? – Joseph Marikle Commented Jul 27, 2018 at 15:40 - @JosephMarikle [{ "a": 3 }, { "b": 2 }, { "c": 1 }] is the expected output and I was trying it with forEach loop for both arrays which i knew was wrong, thats why asked here. – capnam Commented Jul 27, 2018 at 20:53
4 Answers
Reset to default 3You 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}
.
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;
})
);
One option is to use set
on target, this will make it easier to check if the set has
a certain element. Use filter
to filter the source
array.
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);
There are different was to do this.One of them using filter is as below:
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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744773549a4592909.html
评论列表(0条)