Skip to content Skip to sidebar Skip to footer

Loop Through List Of Maps To Filter Map Key-values Using JS

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')

Solution 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)

Solution 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>

Solution 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


Post a Comment for "Loop Through List Of Maps To Filter Map Key-values Using JS"