简体   繁体   中英

get JSON object from knockout observable array by objects id

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?

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM