首页 > 解决方案 > 如果属性不总是存在或未定义,则循环遍历对象

问题描述

我想在 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;

您是否知道构建这种确切类型的数组的任何其他方法或如何解决缺少属性的问题?

标签: javascriptreactjsobject

解决方案


我不知道我是否完全理解了这个问题。

在深度引用的情况下,如果我不想或不能使用任何条件检查,我只需将对象路径引用放在 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);
  }
}

也许它可以解决你的问题。


推荐阅读