I'm trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new one, or append data to an existing one.
I've found a few similar questions but none of the answers worked so I'm a bit stuck. It always ends up finding it doesn't exist and creating duplicate keys.
I have the following code, where xxx
is where I need to check if the key exists:
var groups = [];
for (var i=0; i<something.length; i++) {
var group_key = 'group_'+something[i].group_id;
if (xxx) {
// New group
var group_details = {};
group_details[group_key] = {
group_name: something[i].group_name,
items: [
{ 'name': something[i].name }
]
};
groups.push(group_details);
} else {
// Existing group
groups[group_key].items.push({
'name': something[i].name
});
}
}
The something
I am passing in, is pretty simple, basically in the form of:
[
{
group_id: 3,
group_name: 'Group 3',
name: 'Cat'
},
{
group_id: 3,
group_name: 'Group 3',
name: 'Horse'
},
{
group_id: 5,
group_name: 'Group 5',
name: 'Orange'
}
]