AngularJS: Exploring the Depths of Nested Object Loops

{

    name: 'Product One',
    visibility: 1,
    weight: '0.5',
    price: '19.99'
    custom_attributes: [
        {
            attribute_code: 'image',
            value: '.img'
        },
        {
            attribute_code: 'special_price',
            value: '13.99'
        }
    ]

},
{

    name: 'Product One',
    visibility: 1,
    weight: '0.5',
    price: '19.99'
    custom_attributes: [
        {
            attribute_code: 'image',
            value: '.img'
        },
        {
            attribute_code: 'special_price',
            value: '13.99'
        }
    ]

}

Is there a way to access the 'special_price' value within ng-repeat or in JavaScript?

Answer №1

There are several ways to tackle this issue.

Organize the data in the controller

function ExampleCtrl (products) {
  this.$onChanges = (changes) => {
    if (changes.products) {
    this.specialProductPrices = this.products.reduce((map, product) => {
      map[product.id] = product.custom_attributes
        // @TODO: Consider scenarios where there is no special price.
        .find(({attribute_code}) => attribute_code === 'special_price').value;
      return map;
    }, {})
    }
  }
}

angular.module('foo').component('example', {
  bindings: {
    products: '<'
  },
  controller: [
    ExampleCtrl
  ],
  template: `
    <div ng-repeat="product in $ctrl.products track by product.id">
      Name: <span ng-bind="product.name"></span>
      Price: <span ng-bind="product.price"></span>
      Special Price: <span ng-bind="$ctrl.specialProductPrices[product.id]"></span>
    </div>
  `
})

Using the component like so

<example products="products"></example>
follows AngularJS conventions and optimizes performance by preparing data efficiently.

Utilize it within the loop in the template

If necessary, you can include it directly in the template:

<div ng-repeat="product in $ctrl.products track by product.id">
  Name: <span ng-bind="product.name"></span>
  Price: <span ng-bind="product.price"></span>
  Special Price:
  <span>
    <span ng-repeat="customAttribute in product.custom_attributes track by customAttribute.attribute_code"
      ng-show="customAttributeattribute_code === 'special_price'"
      ng-bind="customAttribute.value">
    </span>
  </span>
</div>

However, this approach may not be efficient as it generates unnecessary DOM elements that will remain hidden (ng-if cannot be used with repeaters here). It could also become highly inefficient with numerous custom attributes.

Alternative approaches

Consider creating components that handle product.custom_attributes or developing a filter that extracts the attribute. These methods offer more flexibility but require further implementation.

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

Display JSON information in the present moment

I am looking to display only 2 results from a JSON file based on the current time. For example, at 11:00 am today, I want to show only the second and third items. JAVASCRIPT $(data.users).each(function() { var output = "<ul><li>" + this.first ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at https://i.sstatic.net/bDU7X.png The benefit of rendering JSON in string format within the page response is that it allow ...

How can a function be restricted to only one button for Bootstrap-5 scrolling to the bottom of modals?

I am working on creating two buttons with different functionalities: 1: to open a modal window 2: to open the same modal and automatically scroll to the bottom Here is the code snippet: $('#menu-item-6706').on('click', function (){ ...

Is there a way to implement a timeout for redirection or new pages opened on a different server?

Is there a way to redirect my page to another website, like google.com, or to open google.com as an additional page in the browser? In addition, is there a way to close any previously opened google pages (if opened as a new page) or return to my page (if ...

Tips for customizing the background-image path in CSS modules for Next.js v14 during development and production

I am currently utilizing Next.js version 14 to construct a webpage with the setup showcased in the image provided below. https://i.sstatic.net/IMxlm.png Within my index.module.scss file, I have integrated an image for the background design. The snippet ...

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

Incorporate a FontAwesome Icon into your jsPdf Document

I recently updated to the latest version of jspdf.debug.js. Unfortunately, when I try to render FontAwesome icons in a PDF document, they are not displaying properly. I have added a user icon using FontAwesome on my webpage and included an image for refer ...

Creating an array of objects with string keys in JavaScript can be achieved by defining an array

In order to simulate a response from the server, I would like to use keys such as 1.0.0 instead of default indexes. This will result in something like the example below: https://i.sstatic.net/JUzjf.png I attempted using { 'versions': [ '1. ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

Bootstrap 4 tabs function perfectly in pairs, but encounter issues when there are three of them

Having trouble with bootstrap4 tabs not working properly? They function well with 2 tabs using the code below: <div class="row"> <div class="col-12"> <ul class="nav nav-tabs" id="registration-picker-acc-select" role="tablist"> ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

How come I'm encountering issues when trying to click on the "register-selection" button in my Bootstrap and JS setup?

I am facing a challenge while developing my website. I want to trigger an alert when the "register-selection" is clicked, but despite trying both Jquery and vanilla Javascript, I have not been successful. Even after searching online resources and ChatGPT f ...

In Vue JS, what is the best way to update a Child component after clicking a button on the Parent Component?

In my application, I have a setting option that updates from the Parent Component. The setting data is saved in localStorage and three Child Components utilize this setting data. <P> <c1> </c1> <c2> </c2> <c3> < ...

Having trouble with Onsen UI + React Navigator pushPage function?

After experimenting with the Onsen playground and React Combining Navigator and Tabbar example, I created this unique animation: I decided to reposition the button and input field for adding more users by using a fab. However, when I attempted to call nav ...

The click event for jQuery is failing to trigger on every link

Currently, I'm in the process of creating a "collapse all" button for the Bootstrap 3 collapsible plugin. It appears to be functioning correctly, but only when there is just one collapsible on the page. Once I add another one, the method only works on ...

What causes the unusual format of my PHP post function when it is received in NodeJS Express?

Hey everyone, I'm new to PHP and I'm working on a function that posts data to my NodeJS Express backend API. When I received the req.body, it had an extra { jsonObj :""} appended to it. {{"name":"PHP Game test",&quo ...

Ways to determine if an object contains an array

Looking at the following data structure: [ 13, { a: [ [ '2988.30000', '0.19000000', '1549294216.653040' ] ] }, { b: [ [ '2988.30000', '0.00000000', '1549294216.653774&a ...

Issues surrounding the use of [Serializable] in PetaPoco Entities within the context of WebApi

I have encountered an issue while using the [Serializable] attribute with a PetaPoco Entity in order to store it in a REDIS Cache. When I add the [Serializable] attribute to the PetaPoco Entity class, it allows for caching with a REDIS Caching provider bu ...

Create a Buffer that includes all the characters of the alphabet when converted to

My current project involves using Node.js to generate secure, random tokens. Here is a snippet of the code I'm using: crypto.randomBytes(32).toString("hex"); // dd89d6ab1a7196e8797c2da0da0208a5d171465a9d8e918d3b138f08af3e1852 Although this method wo ...

Are you interested in using jQuery and/or AJAX to retrieve the latest images from a website?

I had to utilize a Wikipedia API in order to retrieve images from the New Jersey website, and I devised two methods to carry out similar tasks. The initial approach involved using JSON, but it ended up pulling the entire page content. <script type="tex ...