What is the best method for accessing data from an Array of Objects in AngularJS?

I am trying to call a REST service and display data based on the regInventoryId. I have successfully displayed some objects, but I am having trouble populating the view for SubpartId. Any suggestions or feedback would be greatly appreciated.

Here is the code I have tried so far...

HTML

<div class="row">
        <div class="col-md-6">
            <h5>
                <strong>Rule Id</strong>
            </h5>
            <div>{{lrrDetail.ruleIdentifier}}</div>
        </div>
        <div class="col-md-6">
            <h5>
                <strong>SubpartID</strong>
            </h5>
            <div>{{lrrDetail.subPartId}}</div>
        </div>
    </div>
    <hr class="modalHr"></hr>
    <div class="row lrrDetailboxMrgn">
        <div class="col-md-6">
            <h5>
                <strong>Rule Internal or Outsourced</strong>
            </h5>
            <div>Rule internal data</div>
        </div>
        <div class="col-md-6">
            <h5>
                <strong>Subpart Internal or Outsourced</strong>
            </h5>
            <div>LRR Data one lorem ipsum</div>
        </div>
    </div>

CTRL.JS

  $scope.lrrDetailWinOptions = lrrSearchGridConfig.modalLrrConfig;
    $scope.showDetail = function (id){
      $scope.selectedId = id;
      lrrDetails.findlrrDetail(id.regInventoryId).then(function(response){
        $scope.lrrDetail = response.data;
        $scope.$broadcast('openDetailWindow');
      });

    }

FACTORY.JS

  findlrrDetail: function(regInventoryId){
        return $http.get('/third-party-management/rest/lrr/' + regInventoryId);
    },

};

JSON.JS

0: {subPartId: "99996", regInventoryId: 38468, citationId: "94181", coreCitationId: "69502",…}
assigned: false
citationId: "94181"
citationValue: "New Jersey Statutes 46"
coreCitationId: "69502"
issuingAuth: "New Jersey Legislature"
regInventoryId: 38468
regInvetoryName: "Document Signing & Notary"
regInvetoryNameKey: 4074
regionName: "United States,"
ruleIdentifier: "17181"
ruleName: "Property"
subPartId: "99996"
subPartRuleInvortyKey: null
subpartCitation: "New Jersey Statutes 46:14-6.1"
subpartRuleName: null

JSON1.JS

applicabilityIndicator: "0"
auditGroupCategory: null
auditGroupIndicator: "0"
citationAsOfDate: 1385355600000
citationCoreIndicator: "69498"
citationValue: "New Jersey Statutes 46"
createdBy: "ERDSYSTEM"
createdDate: 1387240599333
enterpriseReportingHierarchies: []
externalIndintifier: "94177"
geographicLocations: [{id: 5670, sourceFeedKey: 5, lookupCode: "RS_ACTIVE", externalIndintifier: "226",…}]
0: {id: 5670, sourceFeedKey: 5, lookupCode: "RS_ACTIVE", externalIndintifier: "226",…}
highValueSummary: "Title 46 of the New Jersey statutes provides property laws."
id: 38468
issuingAuthority: {id: 13853, agencyCode: "NJ Leg", agencyName: "New Jersey Legislature",…}
agencyCode: "NJ Leg"
agencyName: "New Jersey Legislature"
id: 13853
issuingAuthName: "New Jersey Legislature"
lookupCode: "RS_ACTIVE"
modifiedDate: 1421072858363
mofifiedBy: "ERDSYSTEM"
regInventoryRuleSubPart: null
regulatoryInventoryClassfication: {id: 8001, classificationName: "Compliance", sponserWrokerKey: 209161}
classificationName: "Compliance"
id: 8001
sponserWrokerKey: 209161
regulatoryInventoryName: {id: 4074, inventoryName: "Document Signing & Notary", erhKey: 17844, regInvetoryclassKey: 8001}
erhKey: 17844
id: 4074
inventoryName: "Document Signing & Notary"
regInvetoryclassKey: 8001
ruleIdentifier: "17181"
ruleName: "Property"
sourceFeedKey: 15
subpartCitationCount: 4
subpartCitationIndicator: "0"
subpartCount: 4
vedourActivityDescription1: null
vedourActivityDescription2: null
vedourActivityType: "Both"

Answer №1

If you frequently perform find-then-filter operations, consider exploring Underscore.js, an incredibly helpful library. Utilize its _.findWhere() function in the following manner (referring to your json.js array as json1):

$scope.lrrDetailWinOptions = lrrSearchGridConfig.modalLrrConfig;
  $scope.showDetail = function (id){
    $scope.selectedId = id;
      lrrDetails.findlrrDetail(id.regInventoryId).then(function(response){
      $scope.json2 = response.data;
      $scope.lrrDetail = _.findWhere($scope.json1, {'regInventoryId':$scope.json2.id});
      $scope.$broadcast('openDetailWindow');
  });
}

This will retrieve the first matching item in the json1 array. The syntax for accessing the correct value from the json2 array may vary. Experiment by using console.log(response.data) until you locate the desired value. For instance, you could attempt something like

console.log(response.data[0].id);

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

Error encountered during JSON object conversion

How can I convert the string below into an object? "{"taskStatus":"Not Started","taskFields":{"originalTransactionDate":"${datafield:feerefund:originalTranDate}","transactionPostingDate":"${datafield:feerefund:tranPostingDate}","referenceNumber":"${data ...

When employing autoForm in Bootstrap 4, where is the "form-control" class established?

Currently, I am working on developing a personalized autocomplete type feature for the afQuickfield in my Meteor project. The main issue I am facing is that when I specify the type="autocomplete" on the afQuickfield, the class="form-control& ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

Is it possible to load a jQuery Mobile dialog without the header?

Within my jQuery Mobile website, I have a button in the header that looks like this: <a href="/foo.html" data-rel="dialog" data-icon="grid">Foo</a> The issue arises when JQM requires me to redeclare the head section with all scripts and CSS. ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

How come my diary section (5th) is showing up/operating in my teacher's section (4th)?

My journey with HTML, CSS, and Javascript began as a beginner. After following a tutorial on YouTube and making some modifications, everything was running smoothly until the diary section unexpectedly appeared under the teacher's section, which should ...

What is the reason that in Node/Express, you are unable to pass the response object to a helper function for tasks like validation in order to prevent the ERR_HTTP_HEADERS_SENT error from

My web app is built using Node (v.18.2) and Express (v. 4.18). Users can make POST requests, which I validate upon arrival. If a user makes an error, I send back an error message to inform them of what went wrong. In order to streamline this process, I de ...

No tests were found to run when Karma was executed using the ng test command

I'm facing an issue with my Angular 10 project where Karma is not detecting my default and custom spec.ts files for execution. Any ideas on why this could be happening? Here is a snapshot of my unchanged Karma Config file: // Karma configuration file ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

Issue in insert.php file: stdClass::$variable property is undefined when using Ionic, Angular, and PHP together

There are three files. Once the submit button is clicked on the Ionic page, all inputs will be sent to the controller, which will then parse them to insert.php. The form input data is saved successfully when only using HTML (without Ionic content), however ...

Error: Encountered an unexpected asterisk symbol while trying to import a Sequelize model from the

Currently, I am developing an application that requires me to connect and run queries on an SQL server using Sequelize. I have set up migrations, seeders, and models by utilizing sequelize init. However, when attempting to generate model objects with const ...

Sort data by various categories using Vue.js

I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js. Here's the template I'm working with: <select v-model="selectedCategory" multiple> <option :value="n ...

The HTTP request fails to execute after a day or two on RHC platform

We have a Node JS - Express application running on an Openshift RHC v2 server, and we make an API call to a third-party SMS gateway whenever a user requests for an OTP. We use a simple $http call to trigger an SMS with the OTP message to the specified numb ...

Is there a way to retrieve the timestamp of a DOM change event when using MutationObserver for event tracking?

Currently, I am successfully using MutationObserver to monitor changes in the DOM. However, I would like to include a timestamp for each event. Unfortunately, there doesn't seem to be a timestamp property available in the MutationRecord. https://deve ...

Using a Fake Timer to test the setTimeout function for a class method is not possible

One way to test setTimeout with a normal function is by using the following code: function doAsync() { setTimeout(doAsync, 1000) } jest.useFakeTimers() test("setTimeout with function", async () => { doAsync() jest.advanceTimersByTime(2 ...

Locate the row just before the last one in the table

I have a table that dynamically creates rows, and I need to locate the second to last row in the table. HTML Code <table class="table"> <tr><td>1</td></tr> <tr><td>2</td>< ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Setting response character encoding in Node.js/Express - how is it done?

Assume I have the following code: app.get('/json', function(req, res) { res.set({ 'content-type': 'application/json' }).send('{"status": "0"}'); }); I've been attempting to send the response as ...

Exploring Angular.js: How to propagate model changes from a child controller within an ng-repeat loop?

I'm facing an issue in my Angular application where changes made to data inside a child controller's form are not being reflected back in the parent array after saving using Restangular. I have tried using debounce to auto-save the data, but it s ...

Utilizing interpolation within various function invocations

componentDidMount() { let env = clientConfiguration['Environment']; let x = `communitiesApi.${env}`; fetch(clientConfiguration[x]) .then((response) => { return response.json(); }) .then(data =& ...