当在数组中找到关键字时,在对象中循环以提取属性名称的问题

Issues looping through an object to pull out property names when a keyword is found in an array

本文关键字:提取 属性 问题 循环 数组 关键字 对象      更新时间:2023-09-26

我是一个自学编程的新手,使用angular、node.js和图形数据库noe4j开发web应用程序。

我正试图使用下划线库方法_.contents来提取标签数组中包含"核心"标签的术语的名称。我一直在努力找出正确的语法,任何指针都将不胜感激(包括避免在SO上提出恼人的语法问题的方法)。

我想我要么对循环如何通过对象有问题(每个"项"都由一组{}中包含的内容组成吗?),要么我试图识别循环中密钥的方式完全不正确。

返回数据样本样本:

[{"name":"Sciences","labels":["Term","Science"]},{"name":"Image","labels":["Type","Image","Core"]},{"name":"GIF","labels":["Type","Image"]},{"name":"Infographic","labels":["Type","Image"]},{"name":"Chart","labels":["Type","Image"]},{"name":"Photo","labels":["Type","Image"]},{"name":"Microscope","labels":["Type","Image"]},{"name":"Telescope","labels":["Type","Image"]},{"name":"Text","labels":["Type","Text","Core"]}]

角度控制器:

    function typeCtrl($scope, $http) {
    $http({method: 'GET', url:'/query/type' }).
        success(function(data){
            var theList = [];
            for(var item in data) {
                if (window._.contains(item.labels, "Core") === true) {
                    theList.push(item.name);
                }
            }
            $scope.display=theList;
            $scope.test = theList;
        }).
        error(function(data){
            $scope.type="Error :("
        });
};

您的数据是一个数组,而不是一个对象,因此for(var item in data)会为您提供类似0,1,2的索引,这可能是的问题

所以你应该使用

for(var i=0;i<data.length;i++)

要查找标签数组是否包含Core,可以使用方法的基本indexOf

function typeCtrl($scope, $http){
    $http({method:'GET', url:'/query/type'}).
        success(function(data){
            var theList = [];
            for(var i=0;i<data.length;i++){
                if (data[i].labels.indexOf("Core") > -1){
                    theList.push(item.name);
                }
            }
            $scope.display=theList;
            $scope.test = theList;
        }).
        error(function(data){
            $scope.type="Error :("
        });
};

请参阅样品小提琴以了解差异:http://jsfiddle.net/jmBjD/