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

Passing a variable between functions in JavaScript: Tips and tricks

let chart; let data = new Array(); function handleClick() { data = document.getElementById('graph:hi').value; alert(data); } let chartData = new Array(66, 15, 2.5, 21.9, 25.2, 23.0, 22.6, 21.2, 19.3, 16.6, 14.8); alert(chartData); jQuery ...

Unexpected behavior from Bootstrap within React

I recently started working on a React project that I initiated with the create-react-app command. To incorporate Bootstrap into my project, I added the necessary CDNs to the public/index.html file after generating the project. <link rel="stylesheet" hr ...

Activeadmin prefers angular js routes over rails routes

My current application utilizes Rails 3.2.17 and AngularJS. I am interested in integrating Activeadmin into the existing setup. To achieve this integration, I followed the guidelines outlined in a blog post on Activeadmin by Ryan Bates. Here are the steps ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squa ...

Utilizing modals for form validation in Angular

Having trouble implementing form validation within a modal pop up? Read on for some guidance. In my view, here is an example of how the form is structured: <script type="text/ng-template", id="modalVideoNew"> <div class="ngdialog-message"> ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

Creating variables in Typescript

I'm puzzled by the variable declaration within an Angular component and I'd like to understand why we declare it in the following way: export class AppComponent { serverElements = []; newServerName = ''; newServerContent = &apos ...

Getting the chosen option from a dropdown list mapped in ReactJS

I am working on a dropdown select option that is linked to the data of an array object called 'template_titles'. Currently, the value in the dropdown corresponds to the title in the object. My goal is to be able to extract and use the selected va ...

What is the best way to handle null values in a JSON query?

How can I efficiently exclude null values when pulling data from a JSON file? I am seeking the most straightforward solution for parsing JSON into YAML without encountering formatting issues. Perhaps I am overcomplicating things. Here is the JSON data: { ...

JavaScript hack for improving slow scrolling experience with smooth scroll on Firefox

As a web application developer, I encountered a particular scenario where there are multiple position:fixed elements, canvases, and an overflow:scroll element. Unfortunately, scrolling in Firefox becomes extremely slow when smooth scrolling is enabled. Wh ...

What is the method for including the `meta:redirect` or `<meta http-equiv="refresh" content="0; url=http://example.com" />` in the metadata object for Next.js version 13?

In order to redirect users from one of my pages, I previously utilized the redirect metatag. However, I am unable to locate similar options within the metadata API in Next.js 13 for the appRouter. ...

What is the best way to replace HttpClient in Aurelia?

I am completely new to Aurelia. How can I modify the code below in order to implement a dummy HttpClient, such as a json reader, that will provide a static set of json data without the need for a server during development? import {inject} from 'aure ...

What is the best way to demonstrate that every key within an object possesses the identical type?

I received a JSON response containing various metrics along with their values and confidence levels. I want to represent this data as a JSON Schema and generate beans using JsonSchema2Pojo. { "QPI": { "value": 0.053916827852998075, "co ...

Utilize Python to extract JSON data from a CURL response

I need to extract the value of the id, which is "id": 59 from a JSON output obtained using curl command. The JSON output looks like this: [{"id":59,"description":"This is a demo project","name":"Demo_Project","name_with_namespace":"sam / Demo_Project","pa ...

Utilizing the Twitter API with Next.js to automate tweets even when the website is not actively engaged

Currently, I am utilizing next.js for the development of a web application. My goal is to have this app automatically post to my Twitter account. I have already set up a developer account on Twitter and an API in nextjs. By calling the API, it will trigger ...

Is there a way to emphasize text within a string of object array items?

I am currently utilizing the data provided below to pass as props in React. The functionality is working smoothly, but I have a specific requirement to only emphasize the words "target audience" within the text property. Is there a feasible way to achieve ...