对象数组过滤问题

时间:2017-02-06 12:38:53

标签: javascript angularjs-filter

我有以下JSON作为数组,我试图过滤角色属性,但我无法过滤结果。请帮帮我。

function [  ] = CHECK_FOR_CAP( image )

folder = 'TESTINGFOLDERS/NOCAP';
filePattern = fullfile(folder, '/*.*');
ImageFiles = dir(filePattern);
%crop loaction of cap
imageCROP = imcrop(image,[130 0 100 50]);
%turn to BW
imageBW=im2bw(imageCROP);
%count black pixels
answer = sum(sum(imageBW==0));
%if <250 black, save it to folder NOCAP
if answer<250
     a = length(ImageFiles)-1;
    for j = 1:a
        baseFileName = [num2str(j),'.jpg'];
        filename = fullfile(folder,baseFileName);
        if exist(filename,'file')
            imwrite(image,filename);
        end
        imwrite(image, fullfile(filename));
    end
    disp('NO CAP DETECTED');
end

我写的JavaScript代码如下:

var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];

2 个答案:

答案 0 :(得分:3)

您的data变量有语法错误。您需要删除包装它的引号。

您的过滤代码也有一点变化。

从此改变:

"[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}]";

对此:

[{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"]}];

看到它正常工作:

var data = [{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["CitySupervisor"]},{"roles":["citysupervisor"]},{"roles":["partner"]},{"roles":["citysupervisor"]},{"roles":["partner","supervisor"]},{"roles":["clientsupervisor"], "name": "Jack", "profileId": 34533}];

var results = data.filter(function (user){
	return user.roles.indexOf('clientsupervisor') > -1;
});

console.log(results);

答案 1 :(得分:0)

试试这个,简单的方法

var results = data.filter(function(user) {
    return user.roles.indexOf("clientsupervisor") > -1 ? true: false
});

并从数据对象中删除"",这是数组对象

var data = [{"roles":["citysupervisor"]},.....];