Reputation: 1704
If I try to create a dictionary this way:
var dict = [];
$.each(objs, function (idx, obj) {
dict[obj.category] = obj;
});
Old elements with the same category
are overwritten and each key only has one value, if I do it this way:
var dict = [];
$.each(objs, function (idx, obj) {
dict[obj.category].push(obj);
});
I get an error if the key doesn't exist. How can I solve this problem? I basically want a dictionary which looks like this:
"Category1":{obj1,obj2,obj3},
"Category2":{obj4,obj5,obj6}
Upvotes: 1
Views: 918
Reputation: 68655
It is good to simulate {}
for dictionary, but for dictionary logic it will be better to use Maps to work on higher level of abstraction. Check if the object has a key, if not create and assign to it an array, if already has - just push into it.
const map = new Map();
$.each(objs, function (idx, obj) {
if(!map.has(obj.category)) {
map.set(obj.category, []);
}
map.get(obj.category).push(obj);
});
Upvotes: 2
Reputation: 640
Just use an object.
let dict = {};
dict.Category1 = {};
dict.Category2 = {};
console.log(dict.hasOwnProperty('Category1'), dict.hasOwnProperty('Category3'));
for (item in dict) {
console.log(item, dict[item]);
}
Upvotes: 0
Reputation: 171669
first off use an object since arrays have numeric indexing
Create an array if the category key doesn't exist
var dict ={};
$.each(objs, function (idx, obj) {
// if key exists use existing array or assign a new empty array
dict[obj.category] = dict[obj.category] || [] ;
dict[obj.category].push(obj);
});
Upvotes: 5
Reputation: 386570
You could check if the property exists and if not assign an empty array.
Then push the value.
dict[obj.category] = dict[obj.category] || [];
dict[obj.category].push(obj);
Upvotes: 3