Only when the condition is satisfied in AngularJS will I include JSON data

I have a JSON file named components.json containing information about various board spaces:

{"components": {
    "boardSpaces": [
        {"name":"GO!", "price":0, "position":0, "type":"go"},
        {"name":"Mediterranean Avenue", "type": "property", "price":60, "position":1}, 
        {"name":"Community Chest", "price":0, "position":2, "type":"communityChest"}, 
        {"name":"Baltic Avenue", "price":60, "position":3, "type":"property"},
        {"name":"Income Tax", "price":0, "type":"incomeTax", "position":4},
        {"name":"Reading Railroad", "price":200, "position":5, "type":"railroad"}, 
        {"name":"Oriental Avenue", "price":100, "position":6, "type":"property"}, 
        {"name":"Chance", "price":0, "position":7, "type":"chance"},
        {"name":"Vermont Avenue", "price":100, "position":8, "type":"property"}, 
        {"name":"Connecticut Avenue", "price":120, "position":9, "type":"property"}, 
        {"name":"Jail", "price":0, "position":10, "type":"jail"}]
}}

I am trying to extract objects from the boardSpaces array in the JSON file and store them in an array called self.board, but only if their price is not equal to 0. Essentially, I want to filter out objects with a price of 0.

Below is my AngularJS code for achieving this:

self.board = [];
$http.get('components/components.json').then(function(response) {
    for(space in response.data.components.boardSpaces) {
        if(response.data.components.boardSpaces[space].price !== 0) {
            self.board.push(space);
        };
    };
});

However, when attempting to display this filtered array using ng-repeat in my HTML page, it does not seem to work. The loop works fine without the condition, but integrating the if statement causes issues.

Answer №1

Have you considered utilizing the forEach method for iterating over the array? The syntax seems more intuitive in my opinion:

response.data.components.boardSpaces.forEach(function (element, index) {
    if(element.price !== 0) { // condition: price is not zero
        self.board.push(index); // unsure if you want to store index or element
    };
});

Answer №2

What do you think of this solution?

$http.get('components/components.json').then(function(response) {
    self.board = response.data.components.boardSpaces.
      filter(function(space) {
        return space.price === 0;
      });
});

You can also achieve the same with plain JavaScript in a live example:

var data = {"components": {
    "boardSpaces": [
        {"name":"GO!", "price":0, "position":0, "type":"go"},
        {"name":"Mediterranean Avenue", "type": "property", "price":60, "position":1}, 
        ... (remaining data entries)
]}};

function getData() {
  return data.components.boardSpaces.filter(function(space) {
    return space.price === 0;
  });
}

var terminal = document.getElementById('terminal');

getData().forEach(function(space) {
  terminal.innerHTML += space.name + ' - ' + space.price + '\n';
});
pre {
  border: 1px solid gray;
  background: lightgray;
  padding: 15px;
  margin: 32px;
}
<pre id="terminal"></pre>

Answer №3

The error was due to using for ... in when you should have utilized forEach:

  response.data.components.boardSpaces.forEach(function (space) {
      if(space.price === 0) {
          self.board.push(space);
      };
  });

https://plnkr.co/edit/RmTzQwNjSlh8fVZkyvP2?p=preview

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

"Troubleshooting Image Loading Issues in Next.js: A Guide to Reloading Unresponsive

Hello, I am facing an issue with rendering 300 images from IPFS data. Occasionally, around 3-4 of the images fail to load and result in a 404 error. Even after refreshing the page, these unloaded images remain inaccessible. It seems like they are permanent ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

What are the steps to develop a progress bar using PHP and JavaScript?

In the application I'm developing, PHP and JavaScript are being used extensively. One of my tasks involves deleting entries from the database, which is a time-consuming process. To keep the end-user informed, I would like to provide updates on the pr ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

Protecting String in PHP to Utilize in JavaScript

When I receive code through AJAX, I handle it as shown below: $verifiedSubject = addslashes(htmlentities($_REQUEST['subject'])); $verifiedBody = addslashes(htmlentities($_REQUEST['body'])); $verifiedAttachment1 = addslashes(htmlentitie ...

Struggling to utilize a personalized filter leads to the error message: "Unable to call a function without a designated call signature."

Trying to use a custom filter from an Angular controller is resulting in the error message: 'Cannot invoke an expression whose type lacks a call signature'. I successfully implemented this on my last project, so I'm confused about what coul ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

What is the best way to loop through the contents of this JSON document?

I am looking to create my resume using React. I have a JSON file that includes all my work experience, education, and more. However, I am facing an issue with the way the data is displayed. { "experience":[ { "Title":"Previous Job ...

Unable to retrieve cookies from the client side | Working with NodeJS and JavaScript

Code for Handling Cookies on the Server-Side: res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false }); res.writeHead(302, { 'Location': 'localhost:4000/test', }); res.end(); Code for Acce ...

Tips for applying various CSS properties to a single element using styled-components

Is there a way to style similar elements differently using different CSS properties in styled components? For example: <div></div> <div></div> With the knowledge I have, I can do: export const StyledDiv = styled.div` color: red; ` ...

Restricting the frequency at which a specific key value is allowed to appear in JSON documents

Within my JSON file, there is an array structured like this: { "commands": [ { "user": "Rusty", "user_id": "83738373", "command_name": "TestCommand", "command_reply": "TestReply" } ] } I have a requirement to restrict the num ...

Travis is checking to see if the undefined value is being

My experience with jasmine testing has been successful when done locally. However, I am encountering issues on Travis CI where all the API tests are returning undefined values. Here is an example: 4) Checking Server Status for GET /api/v1/orders - Expecte ...

Using ajax with Django to optimize queries involving select_related() and many to many fields

Seeking help with a view that needs to handle both ajax and regular HTTP requests. Here's a simplified version of what I have: def tag_search(request, tag): items = Item.objects.filter(tags__tagname__exact=tag) if request.is_ajax(): ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, pl ...

$rootsScope.$watch not firing as expected

I am encountering an issue with a watch set in a service (shown in the code snippet below) that is not triggering as expected. Strangely, a similar watch set in a controller using $Scope.$watch is working perfectly when the object changes. What could be c ...

Create a dynamic pulse line on an HTML5 Canvas

Hello everyone, I've been attempting to grasp HTML5 Canvas animation without much success. I was hoping to create the shape below by animating a custom shape every 10 seconds interval. Unfortunately, I got lost in the math and ended up manually writi ...

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...