【发布时间】:2016-08-17 10:05:02
【问题描述】:
首先,我有多个实体,如
国家单位 ----> 客户报告组 ----> 客户
每个国家/地区单位都有不同的客户报告组,而后面的每个单位都有不同的客户
在代码中变量名是
cu ----> crg ---> 客户
这在名为 menuData 的多级对象中表示:
menuData = {
cu1: {
CRG3: {
Customer1: {},
Customer5: {}
},
CRG7: {
Customer3: {},
Customer2: {},
Customer7: {}
}
},
cu4: {
CRG1: {
Customer2: {},
Customer4: {}
},
CRG3: {
Customer4: {}
}
}
};
我想做的是为多级对象中的每个级别构造唯一的 id,例如,客户单位的 id 将是相同的
cu1 和 cu2 等等
对于客户报告组,ID 将由 cu + crg 组成,如 cu1+crg4
为客户:
cu1+crg4+customer6;
我所做的是一个名为 getIds 的函数
var getIds = function(menuData) {
var ids = {};
for (cu in menuData) {
ids[cu] = cu;
for (crg in menuData[cu]) {
if (!(ids[cu] in ids)) {
ids[cu] = {};
ids[cu][crg] = ids[cu].concat(crg);
} else ids[cu][crg] = ids[cu].concat(crg);
for (customer in menuData[cu][crg]) {
if (!ids[cu][crg]) {
ids[cu][crg] = {};
ids[cu][crg][customer] = ids[cu][crg].concat(customer);
} else ids[cu][crg][customer] = ids[cu][crg].concat(customer);
}
}
}
console.log(ids);
return ids;
};
我得到的错误是
无法读取未定义的属性“concat”
我尝试过的是,因为它说它是未定义的,如果它还没有定义,我会尝试定义它
if (!(ids[cu] in ids)) {
ids[cu] = {};
ids[cu][crg] = ids[cu].concat(crg);
}
如果没有定义,定义它并插入值,但是如果它定义了,只赋值 否则 ids[cu][crg] = ids[cu].concat (crg);
为什么会出现此错误?以及如何获取多级对象中的 id ?
编辑,预期输出是
ids = {
"cu1": {
"cu1+CRG3": { "cu1+CRG3+Customer1":{}, "cu1+CRG3+Customer5":{} },
"cu1+CRG7": { "cu1+CRG7+Customer3":{}, "cu1+CRG7+Customer2":{}, "cu1+CRG7+Customer7":{} }
},
"cu4": {
"cu4+CRG1": { "cu4+CRG1+Customer2":{}, "cu4+CRG1+Customer4":{} },
"cu4+CRG3": { "cu4+CRG3+Customer4":{}}
}
}
【问题讨论】:
-
.concat是Array的方法,而不是 MDN 上的ObjectArray.prototype.concat。 -
预期输出是什么?
标签: javascript javascript-objects multi-level