我不确定最好的办法。我想迭代我的json
并找到所有在美国的公司。这个JSON
可能会随着我的应用程序的增长而变得更加复杂,就像在关卡,对象等中一样。我只是想知道人们使用JSON
和{过滤掉数据子集的简单搜索方式{1}}和/或Node.js
或库可能是ES6
等等。
所以,例如这个json,有什么方法可以搜索它并且只撤回那些在美国的公司?
Lodash
答案 0 :(得分:6)
var res = data.filter(v => v.location.country === 'USA');
var data = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location": {
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
}, {
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location": {
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
}, {
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location": {
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}];
var res = data.filter(v => v.location.country === 'USA');
console.log(res);

答案 1 :(得分:2)
您可以使用JavaScript的简单.filter()
方法返回完成过滤器的结果列表。假设您的数据在可变数据中
<强> ES5 强>
data.filter(function(item) {
return item.location.country === 'USA';
});
ES6 :在ES6中,您可以使用与
相同的箭头功能data.filter((item) => {
return item.location.country === 'USA';
});
var data = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location":{
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
},
{
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location":{
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
},
{
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location":{
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}];
var res1 = data.filter(function(item) {
return item.location.country === 'USA';
});
const res2 = data.filter((item) => {
return item.location.country === 'USA';
});
console.log(res1);
console.log(res2);
&#13;
答案 2 :(得分:1)
在lodash中它将是
_.filter(data, function(item) {
return item.location.country === 'USA';
});
答案 3 :(得分:1)
您可以使用原生过滤功能。
const items = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location":{
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
},
{
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location":{
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
},
{
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location":{
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}]
const usItems = items.filter(v => v.location.country === 'USA')