Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids.

I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based on the id being more than 4 digits. In such cases, the full name, name, short name, and id should be removed. For example, if the id is 123456, it along with the name and short name should be filtered out.

app.js

  abc: {
      name: "Momo",
      value: "kls",
      long: "KLSE",
      searchRef: KLSE_SEARCH_REF,
      searchRefURL: "http://www.bursamalaysia.com/searchbox_data.json",

    },

details.js

$ionicLoading.show();

if ($scope.currentMarket == "abc"){

    $webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(function success(response){
        response = JSON.parse(response);
        for (var i = 0; i < response[0].length; i++){
            $scope.searchRef.push({
              name: response[0][i].name || response[0][i].full_name,
              symbol: response[0][i].short_name,
              code: response[0][i].id,
              market: $marketProvider[$scope.currentMarket].long
            });
        }
        console.info($scope.searchRef);
        $ionicLoading.hide();
    });
}

html

<div class="list">
    <div class="item" ng-repeat="item in searchItems" ng-click="openDetail(item)">
        <p>{{item.symbol}} - {{item.name}}</p>
        <p>{{currentMarket | uppercase}}</p>
    </div>
</div>

Answer №1

An elegant solution is to utilize Array.prototype.filter and Array.prototype.map.

$ionicLoading.show();
  if($scope.currentMarket == "abc") {
    $webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(
      function success(response) {
        $scope.searchRef = JSON.parse(response)[0].filter(function(itm) {
            // Add condition for filtering
            return itm.id.toString().length <= 3; 
        }).map(function(itm) {
            // Transform each item
            return {
              name: itm.name || itm.full_name,
              symbol: itm.short_name,
              code: itm.id,
              market: $marketProvider[$scope.currentMarket].long
            };
        });

        $ionicLoading.hide();
      }
    );
  }

Remember to handle errors and ensure your code is defensive.

Answer №2

If your requirement is to filter out ID values with more than 4 digits, you can easily achieve this by implementing a simple condition if(response[0][i].id <= 999). See the example below for reference:

for(var i=0; i<response[0].length; i+=1){
   if(response[0][i].id.toString().length <= 3 ) {
      $scope.searchRef.push(
        {
          name: response[0][i].name || response[0][i].full_name,
          symbol: response[0][i].short_name,
          code: response[0][i].id,
          market: $marketProvider[$scope.currentMarket].long
        }
      );
    }
    }

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

Sending parameters within ajax success function

To streamline the code, I started by initializing the variables for the selectors outside and then creating a function to use them. Everything was working fine with the uninitialized selector, but as soon as I switched to using the variables, it stopped wo ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Physically eliminate (and obliterate) a component from keep-alive

Is there a way to access and programmatically unmount a component instance loaded from Vue Route and persisted using <keep-alive> and <component>? I am working on a dynamic tab system where each tab renders a URL which displays its declared com ...

I need to use JavaScript to create HTML to PDF and then upload the PDF file to a SharePoint Document Library

Our current project requires us to convert HTML to PDF and save it in a SharePoint Document Library. While we have successfully converted the HTML to PDF using Kendo plugin, we are facing challenges with storing it in SharePoint. It's worth noting th ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

Unpacking JSON: Parsing a collection of objects in C#

Currently, I am working on handling JSON responses in my Windows Phone 7 client application. Utilizing Json.NET for deserialization purposes, I am facing an issue with the response object containing a List of products. Upon deserialization, although the s ...

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do ...

How is the same-domain policy applied to popup windows that have JavaScript enabled in the URL?

Is it possible to achieve something similar to this? var w = window.open("javascript: makeAnAjaxRequest();"); I'm curious whether the Ajax request, which is triggered after the new window is opened, would be considered a cross-site request. Does the ...

Assistance needed to translate a single line of C# code into VB for parsing JSON using JToken.Parse

I am experiencing a challenge achieving identical outcomes in VB.Net compared to the C# example referenced on this particular website: The C# illustration yields "Object", however in VB.Net I am obtaining "1". Is there any solution to ensure consistency? ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

What is the best way to tailor specific text in d3.js?

I need assistance with customizing the appearance of an asterisk added to the end of a template literal in d3js. I want to be able to independently adjust the size and color of the asterisk regardless of the variable it's attached to. Below is the cod ...

Exploring the concept of nested dictionaries in web development: how to utilize

Here is a snippet of my JavaScript code: var emotions = {}; $('#emotions').children('#emotionFields').each(function(){ emotions[$(this).find($('.emotion')).val()]=$(this).find($('.value')).val() }); $ ...

How can I transfer form data to a PHP variable using an AJAX request?

Encountering some difficulties, any insights? I have included only the necessary parts of the code. Essentially, I have an HTML form where I aim to extract the value from a field before submission, trigger an ajax call, and fill in another field. It seems ...

I encountered a ReferenceError stating that the variable "html" is not defined

Recently, I delved into the world of Node.js for the first time. During my attempt to connect my index.html file, an error message stating 'ReferenceError: html is not defined' popped up. Below is the code snippet from my index.js: var http = re ...

What is the reason behind $validators not updating the $errors value in ngMessages?

When the validator is called, it returns true/false as expected. However, even when the validator returns false, the html displays the class "ng-valid" instead of "ng-invalid" as needed for ng-messages to function correctly. Using the standard "required" e ...

Developing 2 potential results from textarea input using NODE.JS and HTML

Today, I encountered an issue while working on my bot website project that responds to textarea input. When I attempted to test it with two different commands, one of the commands stopped working unexpectedly. I'm puzzled by this and would greatly app ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

The Enigma of AngularJS Coding

Check out this code snippet. $scope.$watch('year', reloadData); $scope.$watch('month', reloadData); $scope.year = 2017; $scope.month = 1; var reloadData = function() { /* Refresh Data */ } var init = function() { $scope.year ...

The variable (form.onsubmit) remains unset even after assigning a value

function setFormOnSubmit(formName){ if(!formName) return; var form = document[formName]; form.onsubmit = function(){ console.log('This is the onsubmit function'); }; console.log('onsubmit successfully set ...