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

Transferring data from a class method to a React component

Situation: In a React component, I have a class with its own methods that is instantiated. What I'm needing: One of the methods in the class changes the value of an input (referred to as `this.$el`) using `.val()`. However, I need to pass this value ...

Ways to add a prefix to every JSON response in play2 to avoid JSONP vulnerability from potential malicious requests

I'm looking to add a sequence of quotes ("')]}',\n") to all my JSON responses in order to enhance security and prevent JSONP escalation vulnerabilities. Does anyone know how this can be achieved within the play2 framework? I have curre ...

Attempting to iterate through a Query each loop for the Raphael object

I'm currently facing a challenge with creating a jQuery .each() function to iterate through an array that I've constructed from a Raphael object. While I am able to achieve this using a traditional JavaScript for-loop: for (var i = 0; i < reg ...

Display a smaller image preview in the product photo gallery

Hey there! I'm currently working on a website and looking to showcase my product in a similar way as shown here: I would like my main image to be displayed with all the other variants of the product image underneath, along with the same visual effect ...

Click the button to save numerous images at once

We have added two mask images to the page. https://i.sstatic.net/uAbb7.png When a user clicks on a mask image, a file upload dialog box appears, allowing the user to upload their own image and click save. https://i.sstatic.net/V4kFA.png After clicking ...

How can you incorporate AJAX to add a paragraph element to your HTML document?

I have encountered an issue with two files in my project. The first file is an HTML document, while the second file is a PHP file called ajax_access_database.php. Originally, I intended for the PHP file to access a database, but complications arose, leadin ...

A condition in the JSON Schema mandates a specific field based on the value of another

How can a field be made required or non-required based on the value of another field in JSON schema? The JSON schema includes a mode field. If it is set to 'release' or 'debug', the file_path field is optional. However, if it is set to ...

Vue.js error: Trying to access an undefined property

Here is my Vue instance setup: const vueApp = new Vue({ el: '#vue-wrapper', data: { items: [] }}); Utilizing a v-for loop in index.html.eex: <div v-for="item in items[0].subItems">{{ item.name }}</div> In this scri ...

Reviewing file information prior to submission

Is there a way or method we can utilize to validate file details (extension and size) before the form is submitted by the user? I have limited knowledge of jQuery or JavaScript, so please provide detailed assistance if that is the solution. I envision tha ...

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

Angularjs version 1.2 now includes an additional empty option within the select feature

I am encountering an issue with a dropdown menu that is populated with items from a database. The default selection for this dropdown is supposed to be retrieved from a cookie. However, I am facing two problems: 1. There is an empty option as the first i ...

Using a ternary operator to render a span tag in ReactJS

I need to display a number in a span tag with larger font size in Spanish. Here is my React.js code using a ternary operator: <div> {togo !== 0 ? (<div className="text-center"><span className="display-4">{togo}</span>{togo > ...

Creating code that adheres to the ECMAScript 5 standards

In my quest to create a JavaScript library that adheres to modern standards such as HTML5, CSS3, and ESv5, I find myself wanting to break away from the mainstream libraries like jQuery and MooTools. While these are great tools, I believe in the importance ...

Designing a dinner selection with the help of vectors, strings, and arrays by extracting information from two separate text files

After working on this task for a few hours, I seem to be stuck and not making much progress. To begin, I have two text files that I need to read using different functions. For the college.txt file, I need to add its content to a vector of strings. As for t ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Creating a dynamic star rating system using CSS

A unique code pen project showcasing a pure css star rating interface can be found at: https://codepen.io/yaworek/pen/JJpEaZ Below is the custom css part: /*** * Custom Pure CSS Star Rating Widget for Bootstrap 4 * * www.TheMastercut.co * ***/ ...

What is the best way to access elements and attributes from a specific JSON file?

Is there a way to access each property within the JSON data provided? Additionally, I am interested in filtering specific objects based on their IDs. How can this be achieved using the array.filter method in JavaScript? { "records": [ ...

Changing the value of an object property (illustrated using a basic linked list)

I am working on a JavaScript Link List implementation as a beginner, and I have written the following code: var LinkList = function () { this.LinkedList = { "Head": {} }; }; LinkList.prototype = { insert: function (element) { var Node = this ...

Utilizing Ember to transmit models to Bootstrap Popovers

Seeking assistance from anyone familiar with utilizing Bootstrap for Ember components to help resolve an issue. I am trying to understand how to pass a model to the component when using {{bs-bind-popover}} <div {{bs-bind-popover templPop}}>Show pop ...