How do I search for IDs within an array in AngularJS?

Seeking clarification on a somewhat ambiguous question. To provide context, I am extracting the following JSON data:

{
  items: [
    { name: "item 1", options: [1, 2, 3] }, 
    { name: "item 2", options: [2, 3] }, 
    { name: "item 3", options: [1] }
  ],
  options: [
    { id: 1, color: "red" }, 
    { id: 2, color: "blue" }, 
    { id: 3, color: "yellow" }
  ]
}

I'm using ng-repeat to iterate over the items as shown below:

<div data-ng-repeat="item in items">
  <span>{{ name }}</span>
  <ul>
    <li data-ng-repeat="i in item.options">{{i}}</li>
  </ul>
</div>

My intention is to access additional parameters like 'color' within my second ng-repeat loop instead of just numbers. What would be the most effective approach to achieve this? Should I map the options array for each item during initialization to convert each index into the complete object (containing id and color)? Or should I pass the index to the controller, perform a lookup, and then expand the scope with the retrieved option?

Answer №1

If you're looking to retrieve the options linked to your item, a helpful approach would be to create a function specifically for that purpose.

Check out this link for more information!

  <body ng-controller="MainCtrl">
    <div data-ng-repeat="item in items">
      <span>{{ name }}</span>
      <ul>
        <li data-ng-repeat="i in getOptions(item.options)">{{i.color}}</li>
      </ul>
    </div>
  </body>

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { name: "item 1", options: [1, 2, 3] }, 
    { name: "item 2", options: [2, 3] }, 
    { name: "item 3", options: [1] }
  ];
  $scope.options= [
    { id: 1, color: "red" }, 
    { id: 2, color: "blue" }, 
    { id: 3, color: "yellow" }
  ];

  $scope.getOptions = function(options) {
    var rv = [];
    angular.forEach($scope.options, function(option, idx){
       if(options.indexOf(option.id) > -1)
       {
         rv.push(option);
       }
     });
    return rv;
  }
});

Answer №2

<li data-ng-repeat="i in item.options">{{options[i-1].color}}</li>

Update: When the options array is not sorted:

<li data-ng-repeat="i in item.options">{{getColor(i)}}</li>

controller.js:

$scope.getColor = function(i) {
  for(var index=0, len=$scope.options.length; index<len; index++) {
    if ($scope.options.index.id===i) return $scope.options.index.color;
  }
}

Answer №3

To optimize your JSON structure, it is recommended to include the options section in this format:

options: {
    "1": "red", 
    "2": "blue", 
    "3": "yellow"
}

This way, you can easily retrieve the values using their corresponding keys within a JavaScript object:

<li data-ng-repeat="i in item.options">{{options[i]}}</li>

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

Using Vue 3 to send formdata with axios

I've been attempting to upload images to a backend expressjs API using Vue 3. I'm creating a FormData object named "files" and sending it via axios to the server. However, the server isn't receiving anything (req.files is undefined). The ser ...

What is causing the rejection to stay suppressed?

I noticed that when function uploadLogs() is rejected, the expected rejection bubbling up to be handled by function reject(reason) does not occur. Why is this happening? In the code below, a rejection handler for function uploadLogs() successfully handles ...

What is the best way to ensure that a Material UI transition component fully occupies the space of its parent component?

I've been experimenting with a Material UI transition component in an attempt to make it completely fill its parent container. So far, I've achieved some success by setting the width and height to 100% and applying a Y-axis translation for the co ...

Taking in user inputs using Angular 8 reactive forms

My goal is to make my forms function as intended, with multiple forms on each product item having an update and delete option. However, I encountered an issue when adding the [formGroup]="profileForm" directive - the form controls stopped working. This was ...

Sending a jQuery variable to an external PHP script

Utilizing the HTML5 Geolocation API, I am able to retrieve latitude and longitude coordinates which I then need to pass to an external PHP file. This PHP file (getPosition.php) retrieves JSON variables from my database, allowing me to utilize them in geo.j ...

Sign up for and run a JavaScript function within an ASP.NET Page_Load event

Is there a way to both register and run a JavaScript function in ASP.NET during a Page_Load event? I need the function to validate the content of a textbox, and if it is empty, disable a save button. function Validate(source, arguments) { } ...

How can the WordPress Gutenberg Popover be positioned to follow the cursor?

I have a component called Popover that I want to position at the cursor's location. For instance, in a component called RichText, if the user's cursor is at the beginning, middle, or end of a sentence, the Popover should appear depending on the c ...

Compile a roster of service providers specializing in unit testing imports

Recently joining a new team that works with Angular, they asked me to implement unit testing on an existing project built with Angular 8. After researching the best approach, I decided to use Karma + Jasmine for testing. I set up a .spect.ts file structure ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

php json with multiple dimensions

Unable to retrieve the deepest values from my json object, which contains an array of images listed as: { "imgs":[ { "Landscape":{ "2":"DSCF2719.jpg", "3":"DSCF2775.jpg", "4":"IMG_1586.jpg", ...

Angular JS - Sorting with ng-repeat

I'm completely new to AngularJS and facing a filtering issue with a custom function. My goal is to have: Checkboxes for product categories Checkboxes for product sub-categories A showcase of products When a user clicks on a category, the sub-catego ...

What is the best method for converting this API into a JavaScript object?

My goal is to retrieve data from this API: and store it in a JavaScript variable so that when I log the variable inside the browser console, I will see a tree structure related to the API. To better illustrate what I mean, here's an image of the desi ...

ExpressJS authentication -> PassportJS: Issue with setting headers after they have been sent

Currently, I am implementing authentication in Express.js using Passport.js. Below is the code snippet from my login.js file: passport.use(new LocalStrategy( function(username, password, done) { //console.log(username); Usercollectio ...

Transferring Data from Python Script to Browser (with an xserver running on a Linux system)

Looking for suggestions on how to efficiently transfer data from a Python script to a web browser. The Python script, as well as the browser, are operating under an xServer environment in Linux (specifically Raspbian on Raspberry Pi). The script is respon ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

Using ngFor in Angular 6 to create a table with rowspan functionality

Check out this functional code snippet Desire for the table layout: <table class="table table-bordered "> <thead> <tr id="first"> <th id="table-header"> <font color="white">No.</font> </th> <th id="table-hea ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

Implementing a pre-defined value for ajax in ajax programming for beginners

I'm looking for guidance on setting up a hardcoded value for the OnSuccess parameter. The code I'm referencing is not my own, but I believe it may be related to Ajax. I'm a bit confused about it. Specifically, I need to focus on the OnSucce ...

Executing Controller Actions within a JavaScript Timer

Presenting my latest timer: var eventDate = new Date(Date.parse(new Date) + 3600); function countdown() { var elapsed = Date.parse(eventDate) - Date.parse(new Date()); var seconds = Math.floor((elaps ...