Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on its id property. Here's the code snippet I currently have for getting the Id:

self.selectedOrgId.subscribe(function (currentOrgId) {
    alert(currentOrgId);
}, self);

The observable array is populated using an ajax get request and looks something like this:

[
{"userGuid":"37ab100e-f97b-462a-b3f4-79b8fbe24831",
"orgId":1,
"orgName":
"company ltd",
"isHiring":true,
...snip...}
   more...
]

Could someone help me figure out how to search through my array and retrieve the object with the matching orgId?

Answer №1

In order to locate a specific item by its id, you can utilize the ko.utils.arrayFirst method like so:

var itemId = '1';
var selectedItem = ko.utils.arrayFirst(this.items(), function(item) {
    return item.orgId == itemId;
});

Alternatively, you have the option to create a computed property that retrieves the selected item based on its id.

self.selectedItem = ko.computed({
    read : function(){
        return ko.utils.arrayFirst(this.items(), function(item) {
            return this.selectedOrgId() == item.orgId;
        });
   },
   owner : self
});

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

Verifying the functionality of a custom directive in Angular 2 (Ionic 2) through unit

In my ionic application, I developed a custom directive specifically for text masking, aimed at formatting phone numbers within input fields. The core functionality of this directive revolves around utilizing ngControl to facilitate the retrieval and assig ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

Python: Choosing the top 4 items from a JSON array

I'm dealing with a well-organized JSON list that looks something like this: [{ "id": "1", "score": "5" }, { "id": "1", "score": "4" }, { "id": "2", "score": "9" }, { "id": "2", "score": "8" }, { "id": "3", "score": "99" }, { "id": "3", "score": "98" ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Retrieving JSON information from a URI in PHP without relying on cURL

Recently, I encountered a scenario where I needed to retrieve data from a URI returned in JSON format on my IIS machine with PHP. The specific URL was: The challenge was that I couldn't utilize cURL for this task. Is there an alternate method to acco ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

What are the problems with Internet Explorer in Selenium WebDriver?

Currently dealing with a mouse-over issue in IE while using webdriver code. The functionality works smoothly in Chrome and Firefox, however, the problem arises only in IE. How can I resolve this? Initially focusing on an element and then clicking on a li ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Guide on redirecting a server URL to another URL when users access it through a static QR code

Can anyone help me with a dilemma I'm facing? I have static QR codes printed on thousands of boxes that direct to the wrong URL. The designer didn't make the code dynamic, so editing through the generator's interface is not an option. We ar ...

Error: Accessing Undefined Property in Node-SQLite

I recently started developing a REST API for garden-related data collected by an Arduino using node-sqlite3. Basic queries like retrieving all the database information are working fine. However, I am facing challenges when trying to retrieve data based on ...

Conceal virtual keyboard on mobile when in autocomplete box focus

I would like the keyboard to remain hidden when the autocomplete box is focused or clicked, and only appear when I start typing. The code below currently hides the keyboard when any alphabets or numbers are pressed. However, I want the keyboard to be hidd ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

How to troubleshoot an Ionic exception occurring during the execution of any Ionic command?

Whenever I attempt to run an ionic command, I keep encountering this error message: { Error at FatalException.Exception (C:\Users\crist\AppData\Roaming\npm\node_modules\ionic\node_modules\@ionic\cli-u ...

Detect when a user's mouse is hovering over an iframe and escape the iframe accordingly

When the iframe window is visible, there are no issues. However, if the iframe window is set to 0px X 0px in order to hide it while still loading, consider redirecting the iframe or not displaying it at all. In case something is loaded within an iframe or ...

Having trouble parsing a JSON Array containing sub arrays and objects

I am facing an issue with parsing the JSON data. I have tried accessing the JSON array in my MainActivity code, but unfortunately, I am unable to retrieve the details from the first element. Even after logging the arrayList returned from postExecute, it st ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...