What is the proper way to retrieve the correct value in JavaScript?

I'm currently working on an Angular program but I'm having trouble returning the correct value:

function facilityChecked(facility, search) {
    var result;

    search.filter(
        function (v) {
            var rtn = (v["facility_Item"]["text"] == facility);
            if (rtn) {
                var checked = (v.inherit_To_Service === 'true');
                result = checked;
            }
            else {
                result = false;
            }
        }
    );
    return result;
}

In the following code, $scope.parking should be true and $scope.toilet should be false, but they both return as false?

parking = facilityChecked('Parking', rtn.Organisation.Facility);
$scope.parking = parking;

toilet = facilityChecked('Toilet', rtn.Organisation.Facility);
$scope.toilet = toilet;

For more information, please refer to this Plunkr link

Answer №1

This particular function utilizes the filter method to iterate over each item in the array, ultimately assigning the result variable to the last item's value...

To ensure accurate results, initialize the result variable as a starting point, and extract the desired value if found within the item.

function facilityChecked(facility, search) {
    var result = false;

    search.filter(
        function (v) {
            var rtn = (v["facility_Item"]["text"] == facility);
            if (rtn) {
                var checked = (v.inherit_To_Service === 'true');
                result = checked;
            }
        }
    );
    return result;
}

Answer №2

The issue lies in the else part of the search.filter() function. It seems that the function is running for all JSON objects and only returning the value of the last object, which is false. Therefore, it might be unnecessary as you are already extracting values from data.json.

function facilityChecked(facility, search) {
    var result;

    search.filter(
      function(v) {
        var rtn = (v["facility_Item"]["text"] == facility);
        if (rtn) {
          var checked = (v.inherit_To_Service === 'true');
          result = checked;        
        }
      }
    );
    return result;
  } 

For an updated version, check out the Plunker here: http://plnkr.co/edit/SETl5Zqapsdp8FmB6t56?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

Execute a function once the router-view in the App.vue component has been refreshed following a route alteration triggered by vue-router

Is there a way to trigger a function after the contents in <router-view/> within App.vue have been updated following a route change? I attempted using the updated() lifecycle hook, but the function is not being executed. Interestingly, the function ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

Encountered a runtime error in Xcode Swift: Thread 1 terminated due to signal SIGABRT while attempting to display

I need assistance with two issues. 1. I am consistently receiving a signal SIGABRT error and cannot pinpoint the cause. The suggested solutions have not been successful. Project can be found below! 2. After retrieving data from my website, how can I effect ...

The absence of CSV may be attributed to a reference error

I'm new to all of this, so I believe it's a simple mistake on my end, but I can't seem to get it to work. After deploying the code below and clicking on the button, nothing happens. When I inspect the html in my browser, I see an error mess ...

Ensuring user authenticity and automatic redirection when utilizing ajax with PHP

I typically manage user access by directing users to the index page if their session is not valid. As an example: <?php session_start(); if (!isset($_SESSION["userInfo"])) { header("Location: index.php"); } ?> However, I am embarking on ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

Errors in JavaScript are displayed when a React application is built for production

I have developed a client react application using create-react-app. It communicates with a node server that runs an express api. During development, everything was smooth sailing and I was preparing for deployment. After running npm run build, there were ...

What is the best way to extract the ultimate value from this dictionary?

Currently, I am dealing with an API that is providing my Python script with the following data: {"success":"true","message":"","result": [{"Last":"0.00000000","Bid":"42258.06451613","Ask":"100000000.0"}]} Although JSON handling in Python is still new ...

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

What is the best way to iterate through JSON object values using PHP?

How can I iterate through the values of a JSON Object in PHP? $json = '{"1":a,"2":b,"3":c,"4":d,"5":e}'; $obj = json_decode($json, TRUE); foreach($obj as $value) { echo $value; } I'm trying to display abcde, which are the values stored ...

When attempting to pass a token in the header using AngularJS, I encounter an issue with my NodeJS server

Error is: Possibly unhandled Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.res.set.res.header 1. All Node.js services were functioning properly before ...

Django sends back tailored JSON responses that include specific values requiring attention

After receiving a JSON result, it appears that the images section does not correspond correctly with the ID as shown below: { "id": 11 "title":"AAA" "createday":"2015-01-01" "images": [ "B_123.jpg" ], }, { "id": 1 ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

The re-rendering of a functional component utilizing React.useCallback and React.memo() is occurring

I was delving into React concepts and eager to experiment with some new things. Here are a few questions that crossed my mind: Does every functional child component re-render when the parent state changes, even if it doesn't have any props? It seems ...

Converter between JSON formats

Let's consider a situation. The required data format for input and output is JSON. // Input { "OldObject": { "Time": 1351160457922, "Name": "OName", "quantity": 100, "price": 10 } } // Output { "NewObject": { "Time": 1351 ...

Accessing a constant injected into an AngularJs controller from the controller's view: best practices

In my application's app.js, I have the following code: (function () { angular.module('routerDemo', [ 'ui.router', // Routing ]) })(); angular.module('routerDemo').constant('cons ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...