Group Javascript Array Of Objects By Id
What I want to achieve is to group objects together inside an array if the first two digits of the IDs matches. So given the below array of objects, I want to convert this ORIGINA
Solution 1:
You can use reduce()
to return array and one object for grouping.
var data = [{"id":"0100","name":"name 1","message":"Lorem blah blah 1"},{"id":"0101","name":"","message":"Lorem blah blah 1.1"},{"id":"0200","name":"name 2","message":"Lorem blah blah 2"},{"id":"0201","name":"","message":"Lorem blah blah 2.1"},{"id":"0202","name":"","message":"Lorem blah blah 2.2"},{"id":"0300","name":"name 3","message":"Lorem blah blah 3"},{"id":"0301","name":"","message":"Lorem blah blah 3.1"},{"id":"0302","name":"","message":"Lorem blah blah 3.2"},{"id":"0303","name":"","message":"Lorem blah blah 3.3"},{"id":"0304","name":"","message":"Lorem blah blah 3.4"}];
var o = {}
var result = data.reduce(function(r, el) {
var e = el.id.slice(0, 2);
if (!o[e]) {
o[e] = {
id: el.id,
name: el.name,
message: []
}
r.push(o[e]);
}
o[e].message.push(el.message);
return r;
}, [])
console.log(result)
Solution 2:
You could check for double zeroes and add the new group to the result set.
var data = [{ "id": "0100", "name": "name 1", "message": "Lorem blah blah 1" }, { "id": "0101", "name": "", "message": "Lorem blah blah 1.1" }, { "id": "0200", "name": "name 2", "message": "Lorem blah blah 2" }, { "id": "0201", "name": "", "message": "Lorem blah blah 2.1" }, { "id": "0202", "name": "", "message": "Lorem blah blah 2.2" }, { "id": "0300", "name": "name 3", "message": "Lorem blah blah 3" }, { "id": "0301", "name": "", "message": "Lorem blah blah 3.1" }, { "id": "0302", "name": "", "message": "Lorem blah blah 3.2" }, { "id": "0303", "name": "", "message": "Lorem blah blah 3.3" }, { "id": "0304", "name": "", "message": "Lorem blah blah 3.4" }],
grouped = [];
data.forEach(function (a) {
var key = a.id.slice(0, 2);
if (a.id === key + '00') {
this[key] = { id: a.id, name: a.name, message: [] };
grouped.push(this[key]);
}
this[key].message.push(a.message);
}, Object.create(null));
console.log(grouped);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "Group Javascript Array Of Objects By Id"