我可以获取一个对象,但不能在 JS 中获取它的属性
2020-02-24
82
我有一个 ul,其中的 lis 填充了来自
Category
数组的内容。我需要根据单击的 li 访问相应对象的另一个属性(如果我可以在 ul 中获取其索引,这也就足够了,但我还没有找到方法来实现它)。
如果我运行:
var thisCategoryObject = filteredCategories.filter(value => value.name == selectedCategory)[0];
console.log(thisCategoryObject);
但是,这会返回错误。
var thisCategoryObject = filteredCategories.filter(value => value.name == selectedCategory)[0];
console.log(thisCategoryObject.sizeType);
TypeError: undefined is not an object (evaluating 'thisCategoryObject.sizeType')
这可能是一个愚蠢的问题,但有人知道我遗漏了什么吗? 我也无法访问该对象的其他属性。
以下是附加上下文:
class Category {
constructor(name, parent, sizeType) {
this.name = name;
this.parent = parent;
this.sizeType = sizeType;
}
}
var categories = [
// Contains a long list of category objects, some of which are sub-categories of others.
new Category("Electronics", null, null),
..
new Category("Video Gaming Merchandise", "Gaming", null),
..
new Category("Jeans", "Women", "womenTrousers"),
]
// Then the function that renders the appropriate categories, filters the children and displays them once a parent is selected. What I need is to get the .sizeType of the selected category.
var ul = document.getElementById("categories");
var selectedCategory;
var isFashionCategory;
var filteredCategories = [];
function renderCategories(categoryArray){
for (i in categoryArray) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(categoryArray[i].name));
li.onclick = function () {
selectedCategory = this.textContent;
localStorage.setItem('selectedCategory', selectedCategory);
// This will find the Category object with the name of the selectedCategory in the filteredCategories array
var thisCategoryObject = filteredCategories.filter(value => value.name == selectedCategory)[0];
console.log(thisCategoryObject.sizeType);
this.parentElement.innerHTML = '';
filteredCategories = categories.filter(value => value.parent == selectedCategory)
if (filteredCategories.length != 0) {
renderCategories(filteredCategories);
} else {
// window.location.href = '../index.html';
}
};
ul.appendChild(li);
}
}
var startCategories = categories.filter(value => value.parent == null)
renderCategories(startCategories);
2个回答
如果您选择的值不匹配,则会出错。匹配正确时,它将正常工作。请看此示例:
var category = [{
name: "Women",
parent: "Fashion",
sizeType: "Large"
}]
var thisCategory = category.filter(value => value.name == "Women")[0];
console.log(thisCategory.sizeType); //Large
Sukanta Bala
2020-02-24
根据您的代码,
filteredCategories
始终是
[]
循环的第一次迭代,因此您会收到该消息。此外,
filteredCategories = categories.filter(value => value.parent == selectedCategory)
会在其他时候返回
[]
,您会在同一循环的后续迭代中收到相同的消息
malarres
2020-02-24