Reputation: 337
I have an array which looks like this:
var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]
How do I make it to look like this:
[
{tech_id: 11, data: [{id: 1, action:'swim'}, {id: 2, action:'run'}, {id: 5, action:'jump'}] }
{tech_id: 22, data: [{id: 3, action:'climb'}, {id:4, action:'swim'}]}
]
Upvotes: 1
Views: 1437
Reputation: 50639
One suggestion is to use a Map
, where each key in the Map is a tech_id
, and each value is an array of objects (excluding the tech_id
) which have that tech_id
. You can then convert the Map to an array using Array.from with an additional mapping function to convert each [key, value]
pair entry in the map into an object ([tech_id, data]) => ({tech_id, data})
:
const arr = [ {id: 1, tech_id:11, action: 'swim'}, {id: 2, tech_id:11, action: 'run'}, {id: 3, tech_id:22, action: 'climb'}, {id: 4, tech_id:22, action: 'swim'}, {id: 5, tech_id:11, action: 'jump'}, ];
const res = Array.from(arr.reduce((map, {tech_id, ...r}) =>
map.set(tech_id, [...(map.get(tech_id) || []), r])
, new Map), ([tech_id, data]) => ({tech_id, data}));
console.log(res);
.as-console-wrapper { max-height: 100% !important;} /* ignore */
Upvotes: 0
Reputation: 10071
You can use the Array reduce and Object Value function to get it done.
var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]
const result = Object.values(arr.reduce((item, next) => {
if (!item[next.tech_id]) {
item[next.tech_id] = {
tech_id: next.tech_id,
data: []
};
}
item[next.tech_id].data.push(next);
return item;
}, {}));
console.log(result);
Upvotes: 0
Reputation: 2425
You could use reduce
with Object.keys
to do that.
var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]
let mergeObj = arr.reduce((p, c) => {
const {tech_id, ...otherData} = c;
if (!(tech_id in p)) {
p[tech_id] = {
data: []
}
}
p[tech_id].data.push(otherData)
return p
}, {})
mergeObj = Object.keys(mergeObj).map(key => {
return {
tech_id: key,
data: mergeObj[key].data
}
})
console.log(mergeObj);
Upvotes: 2