我有一些数据正在创建2个数组。
控制台没有给我任何错误,但是列表都为空。
这是数据
mydata = {
"id": "661",
"name": "some name",
"description": "some desc",
"subcat": {
"662": {
"id": "662",
"name": "sub 1",
"translations": null
},
"663": {
"id": "663",
"name": "sub 2",
"translations": null
}
},
"image": null
};
这是代码:
chList=[];
thList=[];
thCount=[];
for (var i = 0; i < mydata.length; i++) {
var obj = mydata[i];
var cl = obj.name;
if (obj.subcat != null) {
chList.push(cl);
}
if(obj.subcat) {
if (i < 10) {
var nme = obj.subcat.map( function(item){
return item.name;
console.log(nme);
});
thList = thList.concat(nme);
thCount.push(nme.length);
}
}
}
console.log(thList);
console.log(thCount);
问题是thList和thCount都像这样空着:[]
我该如何确认?
最佳答案
您似乎希望mydata
是一个对象数组,而不仅仅是您提出的对象。如果将呈现给mydata
的对象文字包装在数组中,并可能添加了其他类似的对象,则代码将运行得更好。
其次,obj.subcat.map
将不起作用,因为subcat
也不是数组。您应该将map
应用于Object.keys(obj.subcat)
,然后通过获取的键访问obj.subcat
。
通过这两项调整,它可以工作:
// mydata is an array
mydata = [{
"id": "661",
"name": "some name",
"description": "some desc",
"subcat": {
"662": {
"id": "662",
"name": "sub 1",
"translations": null
},
"663": {
"id": "663",
"name": "sub 2",
"translations": null
}
},
"image": null
}];
var chList=[];
var thList=[];
var thCount=[];
for (var i = 0; i < mydata.length; i++) {
var obj = mydata[i];
var cl = obj.name;
if (obj.subcat != null) {
chList.push(cl);
}
if(obj.subcat) {
if (i < 10) {
// You cannot use map on an object directly. Use Object.keys:
var nme = Object.keys(obj.subcat).map( function(key){
var item = obj.subcat[key]; // get the item by key
return item.name;
// NB: console.log after `return` does not get executed!
});
thList = thList.concat(nme);
// cf. Follow-up question: repeat length as many times:
thCount = thCount.concat(Array(nme.length).fill(nme.length));
}
}
}
console.log(thList);
console.log(thCount);