Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently.

I have 2 JSON files:

images.json

{
    "imageName":        "example.jpg",
    "imageTags":        ["fun","work","utility"]
    "productID":        ["item1","item3"]
}

products.json

{
    "productID":        "item1",
    "productName":      "Staple Gun",
    "productURL":       "Staple-Gun.htm"
}

I haven't written any actual code yet, as I really want to ensure that my setup is solid before diving in.

My objective is to retrieve images based on tags by using a filter on the initial ng-repeat part. This section is functioning well. However, I also want to link to the products featured in the images. The simplest method I came across was to use ng-repeat with the productID as a filter, but if there are 50 photos each with 2 items, it could potentially result in a lot of repetitions. It seems like this could consume a significant amount of resources. Is this the most effective approach, or is there a better way to address this?

Here's a sample of the code:

<div ng-repeat="photo in photos | filter: 'fun'">
   <img ng-src="{{ photo.imageName }}">
   <span>Products In This Image</span>
   <div ng-repeat="product in products | filter: photo.productID">
       <a ng-href="{{ product.productURL }}" title="{{ product.productName }}">{{ product.productName }}</a>
   </div>
</div>

Answer №1

It would be far more efficient to create a simple mapping of the products to an object using the productID as keys.

$scope.product_map = {};
products.forEach(function(item) {
  $scope.product_map[item.productID] = item
});

This code snippet will result in:

{
  "item1": {
    "productID": "item1",
    "productName": "Staple Gun",
    "productURL": "Staple-Gun.htm"
  }
}

Instead of repeatedly filtering through an array whenever you need to find a product, you can now easily access it like this:

var productNeeded = $scope.product_map['item1'];

In the view, this concept translates to:

<div ng-repeat="photo in photos | filter: 'fun'">
   <img ng-src="{{ photo.imageName }}">
   <span>Products In This Image</span>
    <!-- iterate small array of productID's in photo object -->
   <div ng-repeat="id in photo.productID">
       <!-- product_map[id] is a single object reference -->
       <a ng-href="{{ product_map[id].productURL }}" title="{{ product_map[id].productName }}">{{ product_map[id].productName }}</a>
   </div>
</div>

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

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

"Upon refreshing the browser, an Angular map loses its positioning and appears blank

I have implemented a LeafLet map in my Laravel 9 system, which is functioning properly with some exceptions. Here's how it looks like: https://i.stack.imgur.com/kcuVr.jpg The code in the controller (CompetitionsMapController.php) is as follows: ...

Redux is set to return a proxy object in place of the actual state

I'm encountering an issue where I am getting a proxy object when trying to access my initial state in redux. How can I properly access the contents of my state? When attempting to retrieve a large 2D array for a grid, it seems to work fine with small ...

Employing jQuery to populate information into an input field, yet encountering an issue where the data is not being successfully transmitted to

On my page, there is a form with an input box <input name="bid_price" id="bid_price" class="form-control"> If I manually enter a value, it gets posted successfully But when I try to insert a value using jQuery, it doesn't get posted, even tho ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

The server encountered a hiccup during the communication process

Currently, I am utilizing jTable within my jQuery mobile code. I extract parameters from the query string and then bind them to jTable. However, I encountered an error message: "An error occurred while communicating to the server." Here is a snippet of my ...

Is it possible to include two AJAX requests within a single function that both execute when the same submission occurs?

Having one submit button for a function necessitates the running of two ajax functions when the submit button is clicked for validation purposes. <div class="form-group btn-group"> <input type="button" class="btn btn-link" v ...

Maximizing the potential of PJAX with Express and EJS: A guide

Hey there, question coming from a newbie in the world of coding. I've been struggling to make pjax work for quite some time now without any success. The closest I've come is seeing some activity in the terminal, but when I click on the link, it ...

The value 'true' was returned for an attribute 'exact' that is not of boolean type

How can I resolve this warning? Sample Code const Main = (header, navigation) => { return ( <> <div> {navigation !== false && <Navigation />} </div> </> ) } I attempted this soluti ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

Easily choose multiple items at once by searching with react-select

I have implemented react-select to showcase a searchable drop-down list of items where users can select multiple items. The list is lengthy, and users often find it tedious to multi-select many items that match the same filter string. This is because each ...

How to find and return specific collection items in MongoDB by searching for a string

In my mongoDB database, I have stored the following JSON data: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "ID": "1753242", "TYPE": "8003" } }, { "type": "Featur ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Searching for values in an array using the $elemMatch operator in MongoDB 2.6 without the need for the $eq operator

Looking to retrieve all users with a specified objectId in an array. Here is the query I'm using: var query = { 'arrayOfIds': { $elemMatch: { $eq: id } }, }; This query functions well in mongodb 3.0. However, in mongodb 2.6, there isn& ...

Including a null:null entry in the json_encoded data

The following code was not written by me, and unfortunately I do not have the time to update the deprecated calls. <?php $mageFilename = 'app/Mage.php'; require_once $mageFilename; umask(0); Mage::app(); $db=mysql_connect('localhost&ap ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Arrangement of div elements tailored to fit the size of the viewport

I am working on creating a grid of divs that will cover the entire viewport. To start, I want to have a grid that is 7 divs wide and 10 divs high. Below is the code snippet I've written so far to set the size of the div elements: function adjustHeig ...

Ways to retrieve specific data from a JSON object

With the help of NewtonSoft, I successfully convert JSON using the following code snippet: var jtoken = JObject.Parse(stringStuff); Console.WriteLine(jtoken.ToString()); The result is as follows: { "data": { "user": { " ...