javascript - 如果属性不总是存在或未定义,则循环遍历对象
问题描述
我想在 Raect 中建立一个表格,其中包含某个 ebay 列表的排序列表。我发现问题出在这一行:
entriesObj[value][1][0].listingInfo[0].watchCount[0]
因为有时列表根本没有任何手表,在这种情况下,值 watchCount 根本不存在,所以我无法循环遍历它,尽管我尝试使用条件运算符(以及许多不同方式的 if else 语句)它仍然抛出错误。首先我创建了一个对象:
watcherCount = () => {
return (
this.state.itemList.reduce((watcherObject,item) => {
const watcherKey = item.itemId;
if (!watcherObject[watcherKey]) {
watcherObject[watcherKey] = [item];
} else {
watcherObject[watcherKey].push(item);
}
return watcherObject;
},{})
);
}
现在我试图将它们移动到一个数组([手表数量,列表标题,项目 id])以便对它们进行排序:
import React from 'react';
class Watches extends React.Component {
render () {
var entriesObj = Object.entries(this.props.watcherCount);
var sortable = [];
for (var value in entriesObj){
for (var value in entriesObj){
sortable.push([typeof entriesObj[value][1][0].listingInfo[0].watchCount[0] === "undefined" ? "-" : entriesObj[value][1][0].listingInfo[0].watchCount[0], entriesObj[value][1][0].title[0], entriesObj[value][0]]);
}
}
sortable.sort(function(a, b) {
return b[0] - a[0];
});
console.log(sortable);
//Output: Uncaught (in promise) TypeError: Cannot read property '0' of undefined
return <table></table>
}
}
export default Watches;
您是否知道构建这种确切类型的数组的任何其他方法或如何解决缺少属性的问题?
解决方案
我不知道我是否完全理解了这个问题。
在深度引用的情况下,如果我不想或不能使用任何条件检查,我只需将对象路径引用放在 try catch (finally) 块中。
例如(虽然未经测试)
for (var value in entriesObj){
var val;
try {
// just make sure the only error that might be occuring
// here is an object reference error
// therefore the array push happens after the try catch block
val = entriesObj[value][1][0].listingInfo[0].watchCount[0], entriesObj[value][1][0].title[0], entriesObj[value][0]];
} catch(err) {
val = "-";
// log the error or maybe issue a warning since missing items
// is actually expected behaviour
} finally {
sortable.push(val);
}
}
也许它可以解决你的问题。
推荐阅读
- java - 在绘制另一个对象时将一个绘制对象保留在 JPanel 中(Java)
- r - 如何使用列的范围而不是 pmax / pmin 的名称
- lua - Pandoc Lua过滤器:如果参数来自标题(章节或部分),我如何检查函数Str
- python - 创建不同模型对象时如何选择性地指定一个django模型字段值?
- python - NLTK 单词标记除带有破折号的单词之外的所有单词,例如 ('hi-there', 'me-you')
- html - 对齐文本内的图像以适合文本
- php - 已解决:HTML/PHP:阻止提交按钮刷新页面
- android - 如何将 libjpeg-turbo Android NDK 添加为静态库
- c++ - 输入“10d100”之类的内容时导致我的掷骰子脚本崩溃的原因是什么
- c# - 在 Unity 中,如果在 IF 条件下找到组件,请立即使用它