示例JSON:
"employees":[
{"firstName":"John", "lastName":"Doe", "address ": "India "},
{"firstName":"Anna", "lastName":"Smith", "address ": "Europe "},
{"firstName":"Peter","lastName":"Jones", "address ": " Canada "},
{"firstName":"hem", "lastName":"fik", "address ": " Europe "},
{"firstName":"kin", "lastName":"ress", "address ": " India "},
{"firstName":"jack","lastName":"pink", "address ": "Canada "}
]
我想根据地址字段将json数组上面分成多个数组。我的意思是一个JSON数组包含的地址是" India",另一个有下一个等等的员工。
答案 0 :(得分:1)
使用Array.prototype.filter()函数根据条件过滤掉数组元素。
var employees = [{
"firstName": "John",
"lastName": "Doe",
"address ": "India "
}, {
"firstName": "Anna",
"lastName": "Smith",
"address ": "Europe "
}, {
"firstName": "Peter",
"lastName": "Jones",
"address ": " Canada "
}, {
"firstName": "hem",
"lastName": "fik",
"address ": " Europe "
}, {
"firstName": "kin",
"lastName": "ress",
"address ": " India "
}, {
"firstName": "jack",
"lastName": "pink",
"address ": "Canada "
}];
var address = employees.map(function(val) {
return val['address '].trim();
})
var arrays = {};
for (i in address) {
arrays[address[i]] = employees.filter(function(val) {
return val['address '].toLowerCase().indexOf(address[i].toLowerCase()) != -1;
});
}
console.log(arrays);