我想创建一个类似下面代码的对象:
MyObject ={
"United Kingdom":{
"primary":{
},
"secondary":{
},
"service":{
},
},
"France":{
"primary":{
},
"secondary":{
},
"service":{
},
},
我想要做的是自动从数组生成对象,所以我有两个数组:
CountryList = ["United Kingdom", "France"]
MarketList = ["primary", "secondary", "service"]
我是通过for循环
来完成的for (var i = 0; i < CountryList.length; i++) {
for(var p = 0; p < MarketList.length; p++)
MyObject[CountryList[i]][MarketList[p]] = self;
}
但是我收到了一个错误:
Cannot set property 'primary' of undefined
关于我错在哪里的任何想法?它在循环遍历国家/地区列表时运行正常,但是当我想在其中嵌入“市场”对象时,我遇到了问题。
谢谢!
答案 0 :(得分:1)
在为其分配属性之前需要一个对象
myObject[countryList[i]] = {};
提示,大写字母和后面的小写字母表示可以用作构造函数的类或函数。
var myObject = {},
countryList = ["United Kingdom", "France"],
marketList = ["primary", "secondary", "service"],
i, p;
for (var i = 0; i < countryList.length; i++) {
myObject[countryList[i]] = {};
for (p = 0; p < marketList.length; p++) {
myObject[countryList[i]][marketList[p]] = {};
}
}
console.log(myObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您需要添加一个条件来测试MyObject[]
是否未定义。
if (MyObject[CountryList[i]]) {
MyObject[CountryList[i]][MarketList[p]] = self;
}
我认为,你提到的错误将不复存在。
答案 2 :(得分:0)
使用ES6,您可以使用对象解构来获取两个变量,并使用reduce()
来创建该对象。
var MyObject ={"United Kingdom":{"primary":{},"secondary":{},"service":{}},"France":{"primary":{},"secondary":{},"service":{}}}
var result = Object.keys(MyObject).reduce(function(r, e) {
if (!r.CountryList || !r.MarketList) r.CountryList = [], r.MarketList = []
r.MarketList = [...new Set(r.MarketList.concat(Object.keys(MyObject[e])))]
r.CountryList.push(e)
return r
}, {})
var {MarketList,CountryList} = result
console.log(MarketList)
console.log(CountryList)
&#13;