如果我尝试以这种方式创建字典:
var dict = [];
$.each(objs, function (idx, obj) {
dict[obj.category] = obj;
});
具有相同category
的旧元素将被覆盖,并且每个键只有一个值,如果我这样做的话:
var dict = [];
$.each(objs, function (idx, obj) {
dict[obj.category].push(obj);
});
如果密钥不存在,我会收到错误消息。我怎么解决这个问题?我基本上想要一本看起来像这样的字典:
"Category1":{obj1,obj2,obj3},
"Category2":{obj4,obj5,obj6}
答案 0 :(得分:4)
首先使用对象,因为数组具有数字索引
如果类别键不存在,则创建一个数组
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);
});
答案 1 :(得分:2)
您可以检查属性是否存在,如果不是,则分配一个空数组。
然后按下该值。
dict[obj.category] = dict[obj.category] || [];
dict[obj.category].push(obj);
答案 2 :(得分:2)
最好为字典模拟protected static TransactionScope GetTransactionScope()
{
TransactionOptions transactionOptions = new TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
};
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
,但对于字典逻辑,最好使用 Maps 来处理更高级别的抽象。检查对象是否有密钥,如果没有,则创建并为其分配一个数组(如果已有) - 只需按下它即可。
{}
答案 3 :(得分:0)
只需使用一个物体。
let dict = {};
dict.Category1 = {};
dict.Category2 = {};
console.log(dict.hasOwnProperty('Category1'), dict.hasOwnProperty('Category3'));
for (item in dict) {
console.log(item, dict[item]);
}