简体   繁体   English

通过对象ID从可观察的数组中获取JSON对象

[英]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. 除了显示简单字符串数组的ko.observablearrays基本示例外,我什么都找不到。 I have an observable array that holds a largish JSON object with a lot of properties. 我有一个可观察的数组,其中包含一个带有许多属性的大型JSON对象。 I need to get the one of the objects in the array based off on the id property in the array. 我需要根据数组中的id属性获取数组中的对象之一。 I have this code to get the Id: 我有以下代码来获取ID:

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

my observable array is populated via an ajax get request and looks something like this: 我的可观察数组是通过ajax get请求填充的,看起来像这样:

[
{"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? 如何查看数组并获取具有orgId的对象?

When you need to find a specific object based on its id you can use ko.utils.arrayFirst as follow : 当您需要根据其ID查找特定对象时,可以使用ko.utils.arrayFirst ,如下所示:

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. 但是,您还可以创建一个计算属性,该属性将根据所选项目ID返回所选项目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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