Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below:

"PageContentList": [
    {
        "ContentId": 51, 
        "Title": "60 seconds with Rick", 
        "ContentMediaTypeList": [
            {
                "MimeType": "image/png", 
                "MediaTypeName": "Image", 
                "Path": "http://local.admin.solutiaconsulting.com/uploads/4a906d8e-983a-4b54-a627-0e8d48145620.png"
            }, 
            {
                "MimeType": "video/webm", 
                "MediaTypeName": "Video", 
                "Path": "http://local.admin.solutiaconsulting.com/uploads/3a6c56c3-0ef9-4f57-9c84-9caa48a09044.webm"
            }
        ]
    }
]

My goal is to extract different images based on MediaTypeName rather than their position in the list. I am aware of the following methods:

{{:ContentMediaTypeList[1].Path}}

and this:

{{for ContentMediaTypeList}} {{if MediaTypeName == 'Video'}} {{:Path}} {{/if}} {{/for}}

However, the second method feels cumbersome and inefficient. Is there a more efficient way to achieve what I'm trying to do? Thank you for any guidance you can provide.

Answer №1

Hey Charlie, appreciate your response. I made some adjustments to my JSON format:

"PageContentList": [
    {
        "ContentId": 44, 
        "Title": "Company Name", 
        "Gallery": {
            "Images": [
                {
                    "Path": "http://local.admin.solutiaconsulting.com/uploads/9b577ef7-ea8a-42a1-b967-89debbc634c0.jpg", 
                    "MimeType": "image/jpeg", 
                    "ImageWidth": 0, 
                    "ImageHeight": 0, 
                    "AltText": null
                }
            ], 
            "Videos": [ ]
        }
    },
   .... 
]

And for the template:

{{for PageContentList}}
<video id="whatIsSolutiaVideo" class="video-js vjs-default-skin" controls width="{{:Gallery.Images[0].ImageWidth}}" height="{{:Gallery.Images[0].ImageHeight}}" poster={{:Gallery.Images[0].Path}}" preload="auto">
{{for Gallery.Videos}}
<source type="{{:MimeType}}" src="{{:Path}}">
 {{/for}}
 </video>
 {{/for}}

I've structured it so that each JSON data has a specific section for Images, Videos, and more. This makes it easier to input data correctly. Your insights really helped me think this through. Thanks!

Answer №2

It can be challenging to incorporate certain logic in the view, as it is generally not recommended. It is best practice to place your filters in either the model or a controller before rendering.

There is one exception to this rule, which is when you need to limit the number of items displayed. In some cases, limiting items may be appropriate for the view depending on the context.

For example:

Avoid including limits in the view:
- List of questions on a website with pagination options (limit, offset, sorting)

Include limits in the view:
- Displaying attached images for each question where mobile view only shows one image per question, while the desktop view can accommodate up to three images.

Deciding how to structure your application and where to place your logic can vary and is often subject to debates among developers. The approach of separating logic from the view is what I have learned from experience and colleagues, but there are certainly other perspectives out there.

One way to filter data using underscore.js is demonstrated below.

 var videoContent = _.filter(contentMediaTypeList, function(mediaType) {
      return mediaType.mediaTypeName == "video"; 
 });

Check out this JSFiddle link for a working example: http://jsfiddle.net/n98yW/

You can also create a reusable closure for filtering purposes.

var mediaTypeFilter = function(mediaTypeName) {
     return function(contentMediaTypeList) {
           return _.filter(contentMediaTypeList, function(currMediaType) {
                return currMediaType.MediaTypeName == mediaTypeName;
           });
     }
};

Utilize the closure like this:

var videoFilter = mediaTypeFilter("video");    
var videoContent = videoFilter(contentMediaTypeList);

Explore another JSFiddle showcasing the closure solution: http://jsfiddle.net/GA55g/2/

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

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Remove checked rows in a table with a single click

I have created a table with a list and checkboxes next to each element. There is also a Delete button that I want to connect to the delete operation. Here is the code for the Delete button: <tr id="deleteproject" > <td wi ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

When attempting to submit information to a database table, I encounter an error in the browser console: "Uncaught (in promise) Error: Request failed with status code 404."

In my React Node project's login page, I am encountering the following issue. Despite thoroughly reviewing my code after each execution, the error persists. My goal is to pass data from the login page into my MySQL database; this marks the initial sta ...

Error message from BitBucket pipeline indicates that the npm command was not found

Upon deploying code to my server via the Bit Bucket scp pipeline, I encountered an issue with another pipeline meant to install node modules and start the node server. The pipeline returned a failed status and displayed the following error: ./server-run.s ...

Choosing a lone column in amcharts 4

Is there a way to highlight just one column and unhighlight any previously highlighted columns in an amCharts 4 Column chart? I've been attempting to adjust the colors of all the columns before highlighting the target column, but it doesn't seem ...

Unexpected issue with Ionic 4 subarray returning as undefined even though the index is accurate

When attempting to use console.log to view the value, I noticed that the value of noticeSet2[index] is undefined. However, when I print noticeSet, all the data in the array is displayed. Additionally, after printing the index using console.log, it correctl ...

Updating to the latest version of Next.js will result in a modification of the API path

I recently updated my app to the latest version of nextjs (13.1.6) and encountered a problem where all my requests are now failing. It seems that the URL I specified in the request creator, based on the ENV value, is being overwritten. .env file CONST NEXT ...

The perpetual loop in React context triggered by a setState function within a useEffect block

I'm experiencing an endless loop issue with this context component once I uncomment a specific line. Even after completely isolating the component, the problem persists. This peculiar behavior only manifests when the row is discounted and the browser ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

Information does not display in the data tables

In my JSON data, the structure is as follows: $(document).ready(function(){ var dataku = []; $.ajax({ url: base_url+'laporan/load_trx_per_tgl_bukopin', dataType: 'jso ...

Tips on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to: Check for an internet connection; Receive a JSON file from the server and store the data in a file if the server is reachable; Read from the file if the connec ...

Angular library modules for node packages

After developing my latest library, I noticed some red underlines: https://i.stack.imgur.com/ffAjI.png In this package, I plan to incorporate other npm packages like ionic and crypto. I attempted to update the package.json within the library: { "name ...

What is the best way to incorporate the PUT method...?

Within the realm of programming, there exist three distinct files with specific roles - profiles.model.js, profiles.controller.js, and profiles.router.js. The focus now shifts towards implementing the PUT method across these three files. To begin, profiles ...

Is there an issue with the jQuery ajax function when it comes to sending the RegistrationId to our server?

Beginning to work with the pushNotification service for my Android app, I successfully received a registration ID from the GCM server and attempted to send this ID to our server using a jQuery AJAX function. My intention was to send this ID after the user ...

Ways to ensure a function is only triggered once using onmouseover

I'm fairly new to JavaScript and I've been attempting to create a function that only runs once. Here's the logo I've been trying to animate: <img src="img/logot2.png" id="logoutjs" onmouseover="move()" ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Discovering the process to create an onclick function with node.js code

index.html: <html> <h2>Welcome To User Profile Page !!!</h2> <button type="button">Edit Profile</button> <button type="button">Logout</button> </html> On my webpage, I have two buttons - Edit Profile and Lo ...