I have an object. It looks like below:
[
{
\"name\":\"Display\",
\"group\":\"Technical detals\",
\"id\":\"60\",
\"value\":\"4\"
},
{
If you are using lodash, you can use groupBy.
It supports both array and object.
Example:
_.groupBy([6.1, 4.2, 6.3], Math.floor);
// => { '4': [4.2], '6': [6.1, 6.3] }
// The `_.property` iteratee shorthand.
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }
Reduce is great for situations like this. Given list
below is your input data:
const list = [{
'name': 'Display',
'group': 'Technical detals',
'id': '60',
'value': '4'
},
{
'name': 'Manufacturer',
'group': 'Manufacturer',
'id': '58',
'value': 'Apple'
},
{
'name': 'OS',
'group': 'Technical detals',
'id': '37',
'value': 'Apple iOS'
}
];
const groups = list.reduce((groups, item) => {
const group = (groups[item.group] || []);
group.push(item);
groups[item.group] = group;
return groups;
}, {});
console.log(groups);
And if you wanted to be immutable, you could write the reduce
like this:
const list = [{
'name': 'Display',
'group': 'Technical detals',
'id': '60',
'value': '4'
},
{
'name': 'Manufacturer',
'group': 'Manufacturer',
'id': '58',
'value': 'Apple'
},
{
'name': 'OS',
'group': 'Technical detals',
'id': '37',
'value': 'Apple iOS'
}
];
const groups = list.reduce((groups, item) => ({
...groups,
[item.group]: [...(groups[item.group] || []), item]
}), {});
console.log(groups);
Depending on whether your environment allows the spread syntax.
Try
let g = (d,h={},r={},i=0)=>(d.map(x=>(y=x.group,h[y]?1:(h[y]=++i,r[h[y]-1]=[]),r[h[y]-1].push(x))),r);
console.log( g(data) );
let data=[
{
"name":"Display",
"group":"Technical detals",
"id":"60",
"value":"4"
},
{
"name":"Manufacturer",
"group":"Manufacturer",
"id":"58",
"value":"Apple"
},
{
"name":"OS",
"group":"Technical detals",
"id":"37",
"value":"Apple iOS"
}
];
let g = (d,h={},r={},i=0)=>(d.map(x=>(y=x.group,h[y]?1:(h[y]=++i,r[h[y]-1]=[]),r[h[y]-1].push(x))),r);
console.log(g(data));
Use reduce and filter.
lets say your initial array is assigned to data
data.reduce((acc, d) => {
if (Object.keys(acc).includes(d.group)) return acc;
acc[d.group] = data.filter(g => g.group === d.group);
return acc;
}, {})
this will give you something like
{
"Technical detals" = [
{
'group' = 'Technical detals',
'name' = 'Display',
'id' = '60',
'value' = '4'
},
{
'group' = 'Technical detals',
'name' = 'OS',
'id' = '37',
'value' = 'Apple iOS'
}],
"Manufacturer" = [
{
'group' = 'Manufacturer',
'name' = 'Manufacturer',
'id' = '58',
'value' = 'Apple'
}]
}