I have an array of objects, each of which pairs an entry id with a tag id. I'm trying to reorganize this so that I get an object with a single index for each unique entry_id with a corresponding list of the associated tags.
Changing this:
tags_entries = [
{'entry_id': 1, 'tag_id': 1},
{'entry_id': 1, 'tag_id': 2},
{'entry_id': 2, 'tag_id': 1},
{'entry_id': 2, 'tag_id': 3},
{'entry_id': 3, 'tag_id': 1}
]
To This:
entries = {
1:
{
'tags': [1, 2]
},
2:
{
'tags': [1, 3]
},
3:
{
'tags': [1]
}
}
The function I have so far is below, but I'm getting this error with it: Uncaught TypeError: Cannot read property 'push' of undefined, which is coming from the line after the else
function collect_tags(tags_entries) {
out = {};
for (i=0; i<tags_entries.length;i++)
{
out[tags_entries[i]['entry_id']] = {};
if (!out.hasOwnProperty(tags_entries[i]['entry_id']))
{
out[tags_entries[i]['entry_id']]['tags'] = [];
out[tags_entries[i]['entry_id']]['tags'] = tags_entries[i]['tag_id'];
}
else
{
out[tags_entries[i]['entry_id']]['tags'].push(tags_entries[i]['tag_id']);
}
}
return out;
}
Can anyone help me figure out what's causing this? Thanks so much.
['tags']= undefined on the object in else. You aren't copying the entire object intoout[#]. So in the first line of your loop this happensout[1] = {}. Nothing more.