AngularJS offers the ability to filter JSON data with a specified parameter, allowing for precise data

I have a JSON file called datas that contains the following information:

[
    {"value": "1", "text": "aaa"},
    {"value": "2", "text": "bbb"},
    {"value": "3", "text": "ccc"},
    {"value": "4", "text": "ddd"},
    {"value": "5", "text": "eee"},
    {"value": "6", "text": "fff"},
    {"value": "7", "text": "ggg"},
    {"value": "8", "text": "hhh"},
    {"value": "9", "text": "iii"},
    {"value": "10", "text": "jjj"}
]

My goal is to filter data from this JSON file based on an array of "b" values (b0, b1, b3, etc).

$scope.array = {"badge":"1,2,5,7","id":"0","b0":"1","b1":"2","b2":"5","b3":"7"}

For example:

Given an array with b0, b1, b2 and b3 containing the values 1, 2, 5, and 7, I want to retrieve only those specific values from the datas JSON file and display their corresponding text values.

The format of the array may vary, so I need to account for parameters in the form of b+"number".

Here are a few examples:

$scope.array = {"badge":"1,2,3,9","id":"0","b0":"1","b1":"2","b2":"3","b3":"9"}
$scope.array = {"badge":"1,2,7","id":"0","b0":"1","b1":"2","b2":"7"}
$scope.array = {"badge":"1,2,5,7,8,9","id":"0","b0":"1","b1":"2","b2":"5","b3":"7","b4":"8","b5":"9"}

To access the JSON file using AngularJS, I use the following code:

$http.get("/json/datas.json").success(function(data) {
      $scope.datas= data;
});

The values are displayed using ng-repeat.

<div ng-repeat="data in datas">
    <span ng-bind-html="data.text"></span>
</div>

Only the HTML body is displayed:

aaa bbb eee ggg

Answer №1

To tackle this problem, one approach is to manipulate the array containing the "bX" values by filtering, mapping, and/or reducing it in order to generate a lookup table of IDs. This lookup table can then be used to filter the main data array accordingly. However, it's essential to note that the "array" in question is not an actual array; rather, it is a plain object. Therefore, direct application of array methods on it is not possible. To work around this limitation, I utilize Object.keys() to extract its keys into an array. Subsequently, I opt to employ .reduce() to construct the lookup table using keys that adhere to the specified format:

var data = [ {"value": "1", "text": "aaa"}, {"value": "2", "text": "bbb"}, {"value": "3", "text": "ccc"}, {"value": "4", "text": "ddd"}, {"value": "5", "text": "eee"}, {"value": "6", "text": "fff"}, {"value": "7", "text": "ggg"}, {"value": "8", "text": "hhh"}, {"value": "9", "text": "iii"}, {"value": "10", "text": "jjj"} ]

var $scope = {} // demo $scope object
$scope.array = {"badge":"1,2,5,7","id":"0","b0":"1","b1":"2","b2":"5","b3":"7"}

var bVals = Object.keys($scope.array).reduce(function(a, c) {
    if (/^b\d+$/.test(c))
      a[$scope.array[c]] = true
    return a
  }, {})
  
console.log(bVals)

var filteredData = data.filter(function(v) { return bVals[v.value] })

console.log(filteredData)

Answer №2

To filter the data, you can utilize javascript prototype functions map and find. Start by converting the batch properties into an array and then map that array to locate the relevant values

$scope.array = {"badge":"1,2,3,9","id":"0","b0":"1","b1":"2","b2":"3","b3":"9"}
var batchArr = $scope.array.badge.split(',');
$scope.result = batchArr.map(o=> $scope.datas.find(k=> k.value == o)) 

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
$scope.datas = [
    {"value": "1", "text": "aaa"},
    {"value": "2", "text": "bbb"},
    {"value": "3", "text": "ccc"},
    {"value": "4", "text": "ddd"},
    {"value": "5", "text": "eee"},
    {"value": "6", "text": "fff"},
    {"value": "7", "text": "ggg"},
    {"value": "8", "text": "hhh"},
    {"value": "9", "text": "iii"},
    {"value": "10", "text": "jjj"}
]
$scope.array = {"badge":"1,2,3,9","id":"0","b0":"1","b1":"2","b2":"3","b3":"9"}

var batchArr = $scope.array.badge.split(',');
$scope.result = batchArr.map(o=> $scope.datas.find(k=> k.value == o)) 


console.log($scope.result)

$scope.trust = function(html){
 return $sce.trustAsHtml(html);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div ng-repeat="data in result">
    <span ng-bind-html="trust(data.text)"></span>
</div>
</div>

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

Transform all Date fields in the Array to a standardized date format

I have an array with various fields, including a field called dateofbirth. I need to remove the time and change the format to MM-DD-YYYY. var records = [ { "recordno":"000001", "firstname":"Bo", "middlename":"G", "lastn ...

The Script Component is not functioning properly in next.js

While using Tiny Editor, I encountered an issue with defining a key for the editor. According to the documentation, I need to access this key through the tag <script src='address'. This method seems to work fine initially. However, when combin ...

perform asynchronous calls within a for loop in a synchronous manner

Having issues with managing asynchronous events in sails.js. Obtaining data from a JSONapi and attempting to insert it into the database sequentially within a for loop. The goal is to maintain the correct order of execution. For simplicity, consider the f ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...

Exploring the data nesting structure in Grails and mongo DB

I am working on a Grails project that involves interacting with mongo DB. I am seeking advice on the best approach for creating domain classes to represent nested data. Here is an example of the data: settings:{ user:{id:1234 , name:"john"} colors:{h ...

The select2 does not show the selected information

My select2 is not selecting the value when in edit mode. You can view my data here. Upon clicking the edit data button, it should select "settings" as the parent's value, but unfortunately, it's not working. You can see the issue here. Modal Sc ...

Algorithm that continuously increases a given date by 3 months until it surpasses or matches the specified creation date

I am currently working with QuickBase, a platform that involves HTML. My goal is to develop a code that can take a [fixed date] (always in the past) and increment it by 3 months until the MM/YYYY exceeds or equals the MM/YYYY of the [creation date]. Once t ...

What is the best way to add new input fields dynamically using the push() function in AngularJS?

I'm currently working on implementing an add more field feature in angularjs. Here is the code that I am using: Javascript <script> function FruitsController($scope){ var div = 'Apple'; $scope.fruits= ...

Streamlined approach to triggering ng-change on a single textbox

Consider this array within an angular controller: somelist = [ { name: 'John', dirty: false }, { name: 'Max', dirty: false }, { name: 'Betty', dirty: false } ]; To iterat ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Challenges faced while working with Angular JS

Being new to Angular as a UI developer, I find myself struggling with a task at my new job. The company uses Angular JS with JAVA, and I am trying to add a new column to a table on an .html page. Despite my efforts in columns_panel.js, the new column is no ...

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

Is there a universal resolver available for the $routeProvider in AngularJs 1.x?

Can a service be globally resolved for all routes in AngularJs? For example, if I need to retrieve configuration from a Web Service for all the routes, is it possible to achieve something similar to the following pseudocode? $routeProvider .when(&apos ...

The JSX snippet accurately displays the expected value on some pages, but displays an incorrect value on other pages

{_id === friendId || <IconButton onClick={() => patchFriend() } sx={{ backgroundColor: primaryLight, p: "0.6rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: primaryDark }} /> ...

Using protractor and AngularJS to extract text content from two labels by identifying the elements

My app is organized like this: <ul ng-repeat="variable in link.variables" ng-show="SearchboxCtrl.showData" class="ng-scope"> <li class="ng-binding"> Member Since: </li> <span class="ng-binding"> 2010-01-01 </span></ul& ...

The View does not reflect changes made to the scope

Exploring a basic example of what I am attempting to achieve: Athlete.save(athlete,function(result) { $scope.athlete = result.athlete; }); The problem arises when the $scope.athlete variable fails to update in my view. To force an update, I have t ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...