如何从带有角度js的json对象获得结果?

时间:2017-01-12 12:43:31

标签: javascript angularjs json

我有一个json文件,想要按特定值计算行数,并使用angular js模型加载到我的页面。

json看起来像这样:

[
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
]

由$ http服务加载的json文件。

如何在json数据上运行此类查询:

select COUNT(`name`) as a from tbl_ben where ` gender` = 'Female' and `district` = 'LA';

任何想法?

1 个答案:

答案 0 :(得分:2)

您无法在JSON上运行SQL查询,所以让我们在JavaScript中完成它。

我们在数组中有一些数据,我们称之为people

let people = [
    {"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
    {"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
    {"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];

现在,让我们根据查询中的genderdistrict对其进行过滤:

let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));

现在我们可以只检查已过滤数组的COUNT属性,而不是使用length

let count = filtered.length;

我们可以将这段代码抽象成一个很好的函数,它将为我们工作:

let getCount = (array, predicate) => {
    return array.filter(predicate).length;
};

然后我们可以像这样使用这个函数:

let people = [
    {"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
    {"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
    {"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];

getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1

请注意,根据您的示例数据,计数为0,因为您在区"LA"中没有人。