问题描述
如何遍历地图列表以从下面过滤出SearchMap键值使用JS的具有记录地图的列表?
How to loop through list of maps to filter out SearchMap key-values from below List having map of records using JS?
var searchMap = new Map()
searchMap.set("ed_mood", "strong")
searchMap.set("ed_target_audience", "Expert")
searchMap.set("ed_clip_type", "intro")
列表
var master_data =
[
{ed_mood: "Light", ed_rating: 10, ed_target_audience: "Novice", ed_clip_type: "Basic"},
{ed_mood: "Light", ed_rating: 5, ed_target_audience: "Expert", ed_clip_type: "Q&A"},
{ed_mood: "Strong", ed_rating: 8, ed_target_audience: "Expert", ed_clip_type: "Intro"},
{ed_mood: "Strong", ed_rating: 7, ed_target_audience: "Expert", ed_clip_type: "Q&A"},
{ed_mood: "Strong", ed_rating: 10, ed_target_audience: "Expert", ed_clip_type: "intro"}
]
注意:要过滤掉记录,我使用的是AlaSql,但未给出预期的结果.还有其他将地图过滤到地图列表的JS方法吗?
Note: To filter out record I am using AlaSql but it doesn't give expected result. Any other JS way to filter map to list of maps?
var filter_result = [];
searchMap.forEach(function(value, key){
var data = alasql(`select * from ? where ${key} like ?`,[master_data, `%${value}%`]);
$.each(data, (i) => filter_result.push(data[i]));
});
预期结果
[
{ed_mood: "Strong", ed_rating: 8, ed_target_audience: "Expert", ed_clip_type: "Intro"},
{ed_mood: "Strong", ed_rating: 10, ed_target_audience: "Expert", ed_clip_type: "intro"}
]
推荐答案
以下代码过滤
master_data
仅用于 return
Objects
匹配 searchMap
中的每个 param
.
The following code filters
master_data
to only return
Objects
that match every param
in searchMap
.
请参见 Array.prototype.filter()
, Array.prototype.every()
, Map.entries()
, JSON.stringify()
和 String.toLowercase()
了解更多信息.
See Array.prototype.filter()
, Array.prototype.every()
, Map.entries()
, JSON.stringify()
and String.toLowercase()
for more info.
// Search Map.
const searchMap = new Map([
['ed_mood', 'strong'],
['ed_target_audience', 'Expert'],
['ed_clip_type', 'intro']
])
// Master Data.
const master_data = [
{ed_mood: 'Light', ed_rating: 10, ed_target_audience: 'Novice', ed_clip_type: 'Basic'},
{ed_mood: 'Light', ed_rating: 5, ed_target_audience: 'Expert', ed_clip_type: 'Q&A'},
{ed_mood: 'Strong', ed_rating: 8, ed_target_audience: 'Expert', ed_clip_type: 'Intro'},
{ed_mood: 'Strong', ed_rating: 7, ed_target_audience: 'Expert', ed_clip_type: 'Q&A'},
{ed_mood: 'Strong', ed_rating: 10, ed_target_audience: 'Expert', ed_clip_type: 'intro'}
]
// Output.
const output =
// Filter master_data for Objects that include every searchpoint.
master_data.filter((datapoint) =>
// Destructuring assignment + Map.entries to reveal searchMap entries.
[...searchMap.entries()].every((searchpoint) =>
// Object.entries() to reveal datapoint entries.
// JSON.stringify + toLowerCase() for normalization.
JSON.stringify(Object.entries(datapoint)).toLowerCase().includes(JSON.stringify(searchpoint).toLowerCase())))
// Log.
console.log(output)
这篇关于遍历地图列表以使用JS过滤地图键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!