What is the best way to dynamically convert a lodash object (specifically a filter object) into jQuery's listview component?

After referencing the answer to this topic as my first step, which can be found here, my next goal is to utilize a filter function to retrieve all matching entries from a JSON file based on a search term. The objective is to loop through each match and convert them into ordered list items of jQuery listViews with specific CSS formatting.

 function search(data, term) {
  return _.filter(data, function(x) { 
return _.includes(_.toLower(x.title), _.toLower(term))}) 
}

document.getElementById('input').addEventListener('change', function() {
  var name = document.getElementById('input').value;
const data = [{ "video_url": "http://63.237.48.3/ipnx/media/movies/Zane_Ziadi_HQ.mp4", "title": "Zane Ziadi" }, { "video_url": "http://63.237.48.3/ipnx/media/movies/DarBastAzadiHQ.mp4", "title": "Darbast Azadi" }, { "video_url": "http://63.237.48.3/ipnx/media/movies/Cheghadr_Vaght_Dari_HQ.mp4", "title": "Cheghadr Vaght Dari" }, { "video_url": "http://63.237.48.3/ipnx/media/movies/Mashaal_HQ.mp4", "title": "Mashaal" }, { "video_url": "http://63.237.48.3/ipnx/media/movies/Red_Carpet_HQ.mp4", "title": "Red Carpet" } ]

  var result = search(data, name);  // <-- change to use the new search fn
  if (!result) {
    console.log('Nothing found');
  } else {
    console.log('Go to ' + result.video_url);
  var ind = 0;
         listLength = result.length;
 //FIXME 
          listHTML = $.map(result, function(entry) {
           ind++;
     //FIXME 
           if (ind === 1)  {
                return "<li class=\"itemListClass\" id=\"movieListId\" data-theme=\"b\" style=\"padding-top:25px;padding-left: 15px;line-height:70px\"><a style=\"font-size:1.5em;\" class=\"list\"  href='" + entry.video_url + "'>" + entry.title + "</a></li>";
            }else {
            return "<li class=\"itemListClass\" id=\"movieListId\" style=\"padding-left: 15px;margin-left: 10px;line-height:70px\"><a style=\"font-size:1.5em;\" class=\"list\"  href='" + entry.video_url + "'>" + entry.title + "</a></li>";
            }
           }).join('');
       $("#listUl").append(listHTML).listview("refresh").trigger('create');
  }
});

It's important to note that the first item in the listview has a different stylesheet with the data-theme="b" parameter. Additionally, due to hardware limitations, ES6 cannot be used. Therefore, please rely on jQuery and pure JavaScript for your solutions. You are allowed to use lodash .map or any other suitable data types for conversion with specific CSS requirements.

Keep in mind that the listview is populated dynamically from the JavaScript code.

  <input id='input' type='text' placeholder="Search term">
  <ol id="listUl" data-role="listview" data-icon="false"  style="margin-right: 5px;">

Answer №1

When working with an array, you have the option to utilize lodash's isEmpty function to determine if it contains any elements. Additionally, there is no need for a separate counter to keep track of the index since in jQuery map (as well as any map function), the index is automatically available as the second argument.

You can implement something similar to the following:

function search(data, term) {
   return _.filter(data, function(x) {
     return _.includes(_.toLower(x.title), _.toLower(term))
   })
}

document.getElementById('input').addEventListener('change', function() {
   var name = document.getElementById('input').value;
   const data = [{
     "video_url": "http://63.237.48.3/ipnx/media/movies/Zane_Ziadi_HQ.mp4",
     "title": "Zane Ziadi"
   }, {
     "video_url": "http://63.237.48.3/ipnx/media/movies/DarBastAzadiHQ.mp4",
     "title": "Darbast Azadi"
   }, {
     "video_url": "http://63.237.48.3/ipnx/media/movies/Cheghadr_Vaght_Dari_HQ.mp4",
     "title": "Cheghadr Vaght Dari"
   }, {
     "video_url": "http://63.237.48.3/ipnx/media/movies/Mashaal_HQ.mp4",
     "title": "Mashaal"
   }, {
     "video_url": "http://63.237.48.3/ipnx/media/movies/Red_Carpet_HQ.mp4",
     "title": "Red Carpet"
   }]

   var result = search(data, name);
   if (_.isEmpty(result)) {
     console.log('Nothing found');
   } else {
     listHTML = $.map(result, function(entry, i) {
       if (i == 0) {
         return "<li class=\"itemListClass\" id=\"movieListId\" data-theme=\"b\" style=\"padding-top:25px;padding-left: 15px;line-height:70px\"><a style=\"font-size:1.5em;\" class=\"list\"  href='" + entry.video_url + "'>" + entry.title + "</a></li>";
       } else {
         return "<li class=\"itemListClass\" id=\"movieListId\" style=\"padding-left: 15px;margin-left: 10px;line-height:70px\"><a style=\"font-size:1.5em;\" class=\"list\"  href='" + entry.video_url + "'>" + entry.title + "</a></li>";
       }
     }).join('');
     $("#listUl").append(listHTML).listview("refresh").trigger('create');
   }
 });

To see this code in action, you can check out this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Entering in full screen mode

Is there a way to create a first screen appearance that spans the entire screen? I want the whole page to be fullscreen and when someone scrolls down, it transitions to a new screen. I am struggling to find a solution for this. body { margin: 0 0 0 0; ...

tips for using jQuery to compare strings

There is a particular function that I am working on where I need to ensure that the parameters passed in are not duplicated. However, for some unknown reason, this function seems to be running twice. As a result, I have to identify any duplicated parameter ...

What is the best way to retrieve the number of clients in a room using socket.io?

I am using socket.io version 1.3.5 My objective is to retrieve the number of clients in a specific room. This is the code implementation I have: socket.on('create or join', function (numClients, room) { socket.join(room); }); ...

Sort through an array of objects using a different array

I am looking to showcase projects based on specific skills. For instance, if I choose "HTML", I want to see all projects that have "HTML" listed in their array of skills. If I select multiple skills, then only display projects that have those exact skills. ...

Generate a dynamic JSON object using JavaScript and then deliver it back

I'm dealing with a function that is supposed to return a JSON object in this format: this.sampleFunction = (x, filename) => { if (x.isPresent()) { return { 'result': true }; } else { return { 'result&apos ...

Tips for adjusting custom spacing margins within Material UI Grid

Is there a way to adjust the spacing between Grid items in Material UI? Here's the code I currently have: <Grid container spacing={1}> <Grid item xs={6}>Node 1</Grid> <Grid item xs={6}>Node 2</Grid> ...and so ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Command is not displaying JavaScript

Having difficulty grasping the task at hand. As a Mac user, my goal is to construct a 3D portfolio but I'm facing challenges. The issue lies in JavaScript not appearing on Variants. Upon entering "npm init vite.js/app," a framework is generated, follo ...

Generate visually appealing pie charts using custom mysqli queries within Google's charting

While attempting to utilize Google Charts in combination with PHP and MySQLi, I encountered a roadblock. My goal was to create a Pie chart with 3 slices representing different counts based on specific conditions for a Lesson-Activity. However, despite my e ...

The alignment of the label button within the form-group is being set to the top

While using Bootstrap 4, I encountered an issue with aligning the save button in a form group because there was no label at the same level. Despite trying to follow an example from here, I still had to hard code margin-top to prevent the button from bein ...

What causes the "Invalid hook call" error to occur when the useQuery function is invoked?

Encountering an issue while trying to use the useQuery() function from react-admin within a custom component. Despite the clear error message, I'm struggling to determine the right course of action. Visiting the provided website and following the inst ...

Leverage the power of require() beyond the confines of Node

I'm currently exploring how to integrate an Angular.js application with Node.js. At the moment, I have the following code in the file MY-PROJECT/public/js/controllers.js function LoginController( $scope ) { // fetch waiters var Waiter = require( ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

Reorganizing Array from PHP after Decoding Facebook Open Graph

I'm in the process of creating an app that would greatly benefit from suggesting a user's Facebook friends as they type. However, I've hit a roadblock when it comes to converting the Open Graph result (retrieved by accessing a user's fr ...

The functionality of json_encode seems to vary when applied to different PHP arrays, as it successfully encodes data for

My current challenge involves importing three arrays from PHP into JS using json_encode. Below is the code snippet I am currently working on: <?php $query2 = "SELECT * FROM all_data"; $result2 = $conn->query($query2); $bu = []; ...

The error message states: "Cannot serialize object of type DeferredAttribute to JSON"

As I was testing my project, I came across a strange error message: "Object of type DeferredAttribute is not JSON serializable..." Before delving into the error, let me explain what I intended to achieve: Step 1: A registered user shares their refer code ...

What is the best method for creating an HTML table using a Javascript function in PHP?

When working with a PHP file to generate a table based on SQL query results, I encountered an issue where only one incorrect row is returned. If anyone has a basic idea of what might be happening, it would be greatly appreciated. This is my HTML Code: &l ...

PHP Command Line Interface can effectively parse JSON strings provided as arguments

When utilizing PHP 5.3 and passing a JSON encoded string as an argument via command line... /usr/local/bin/php -q /path/to/script.php {"key":"test","cache":1} ... the code within script.php looks like this: <?php print_r($argv); ?> The output is: ...

Testing Vue with Jest - Unable to test the window.scrollTo function

Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect and window.scrollTo? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0. Function that needs testing: export de ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...