Loop through list of maps to filter map key-values using JS

大城市里の小女人 提交于 2021-01-27 19:36:38

问题


How to loop through list of maps to filter out SearchMap key-values from below List having map of records using JS?

Map

var searchMap = new Map()
searchMap.set("ed_mood", "strong")
searchMap.set("ed_target_audience", "Expert")
searchMap.set("ed_clip_type", "intro")

List

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"}
]

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]));
});

Expected Result

[
   {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"}
]

回答1:


The following code filters master_data to only return Objects that match every param in searchMap.

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)



回答2:


The problem in your code is that you are concatenating the conditions using (implicitly) the OR operator. Your expected result suggests that you should use the AND operator.

You could build your SQL command first and then execute it using AlaSQL (just a suggestion, you introduced me to AlaSQL :-) )

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"}
];

var command = "SELECT * FROM ? WHERE";
var values = [];

searchMap.forEach(function(value, key){
	command += ` ${key} LIKE ? AND`;
	values.push('%' + value);
});

//Removing the last "AND"
command = command.substring(0, command.length -4);

var filter_result = alasql(command, [master_data, ...values]);

console.log(filter_result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/alasql/0.4.5/alasql.min.js"></script>

Solution without AlaSQL

Using ES6, your code could be:

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"}
];

var filter_result = master_data.filter(function(x) {
    for (var [key, value] of searchMap) {
        //Change the comparison to fit your needs
    
        // Condition to handle null , undefined and ''(blank) values
        if (x[key] !== null && typeof x[key] !== 'undefined' && x[key] !== '') {
            if (x[key].toLowerCase() !== value.toLowerCase()) return false;
        } else {
            return false;
        }
    }
    return true;
});

console.log(filter_result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/alasql/0.4.5/alasql.min.js"></script>



回答3:


You can use lodash's filter method here.

In your case, you will do:

const result = _filter(master_data, {
  ed_mood: 'strong',
  ed_target_audience: 'expert',
  ed_clip_type: 'intro'
});

Read more about it on lodash/filter



来源:https://stackoverflow.com/questions/49271554/loop-through-list-of-maps-to-filter-map-key-values-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!