简体   繁体   English

如何删除可观察的数组中的“未定义”索引?

[英]How do I remove “undefined” index in a Knockout observable array?

            self.previewApplicationsScreeningQuestions = ko.computed(function () {
                return ko.utils.arrayMap(self.applications(), function (i) {
                    if (i.application.applicationKey == self.previewApplicationKey())
                        return i.application.applicantScreeningQuestionsAndResponses[0];
                });
            });

I declared a viewModel like this. 我这样声明了一个viewModel。 What it does is, it basically loops through the "applications" viewModel and returns its "applicantScreeningQuestionsAndResponses[0]" object when a specific condition is met(not important in this question). 它的作用是,当满足特定条件时,它基本上遍历“应用程序” viewModel,并返回其“ applicantScreeningQuestionsAndResponses [0]”对象(在此问题中不重要)。

When I check the result of this in the console, it gives me. 当我在控制台中检查此结果时,它给了我。

[Object, undefined, undefined, undefined, undefined, undefined, undefined]

I just want to remove all undefined index and just leave one [Object] in the viewModel. 我只想删除所有未定义的索引,只在viewModel中保留一个[Object]。 How can I fix this? 我怎样才能解决这个问题?

EDIT: 编辑:

            self.previewApplicationsScreeningQuestions = ko.computed(function () {
                return ko.utils.arrayMap(self.applications(), function (i) {
                    if (i.application.applicationKey == self.previewApplicationKey())
                        var arr = i.application.applicantScreeningQuestionsAndResponses[0];
                });
                var newArr = new Array();
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i]) {
                        newArr.push(arr[i]);

                    }

                }
                return newArr;
            });

This returns all 'undefined' 这将返回所有“未定义”

you can write somting like below: 您可以像下面这样写草皮:

 self.previewApplicationsScreeningQuestions = ko.computed(function () {
            return ko.utils.arrayMap(self.applications(), function (i) {
                if (i.application.applicationKey == self.previewApplicationKey() && i.application.applicantScreeningQuestionsAndResponses[0]!=undefined)
                    return i.application.applicantScreeningQuestionsAndResponses[0];
            });
        });

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

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