Smita Ahinave Smita Ahinave - 5 months ago 11
JSON Question

Divide JSON Array of objects according to field

Sample 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 "}
]


I want to split above json array into multiple arrays according to address field.I mean one JSON array contains employees having address is "India",another having next and so on.

Answer

Use Array.prototype.filter() function for filtering out the array elements based on condiotions.

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);

Comments