0

I can't find anything but basic examples of ko.observablearrays that show arrays of simple strings. I have an observable array that holds a largish JSON object with a lot of properties. I need to get the one of the objects in the array based off on the id property in the array. I have this code to get the Id:

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

my observable array is populated via an ajax get request and looks something like this:

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

How can I look into my array and get the object with the orgId that I have?

1 Answer 1

4

When you need to find a specific object based on its id you can use ko.utils.arrayFirst as follow :

var selectemItemID = '1';
var selectemItem = ko.utils.arrayFirst(this.items(), function(i) {
    return i.orgId == selectemItemID;
});

But you can also create an computed property that returns the selected item based on the selected item id.

self.selectedItem = ko.computed({
    read : function(){
        return ko.utils.arrayFirst(this.items(), function(i) {
            return this.selectedOrgId() == i.orgId;
        });
   },
   owner : self
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.