在JavaScript中,如何访问对象数组内的对象属性?

时间:2018-08-28 05:41:53

标签: javascript arrays object ecmascript-6

我具有以下对象数组,并且正在尝试访问测试程序交易的金额和状态?

Output

我可以通过以下方式显示公司和项目的名称:

transactions.map((transaction, index) => {
    console.log(transaction.company_name)
    console.log(transaction.project_name)
})

我如何显示tester_transaction对象的状态和数量?

4 个答案:

答案 0 :(得分:1)

您可以直接从.tester_transaction访问transaction对象及其属性(并检查是否定义了tester_transaction):

transactions.map((transaction, index) => {
    console.log(transaction.company_name)
    console.log(transaction.project_name)

    if (transaction.tester_transaction !== undefined) {
      console.log(transaction.tester_transaction.status)
      console.log(transaction.tester_transaction.amount)
    }
})

答案 1 :(得分:1)

transactions.map((transaction, index) => {
    if(transaction.hasOwnProperty("company_name")){
       console.log(transaction.company_name);
    }
    if(transaction.hasOwnProperty("company_name")){
       console.log(transaction.project_name);
    }
    if(transaction.hasOwnProperty("tester_transaction")){
       console.log(transaction.tester_transaction.amount);
    }
    if(transaction.hasOwnProperty("tester_transaction")){
       console.log(transaction.tester_transaction.status);
    }
});

不要忘记检查该属性是否存在。

答案 2 :(得分:0)

    transactions.map((t) => {
    console.log(t. tester_transaction.amount)
  console.log(t.status)
})

答案 3 :(得分:0)

此代码违反了Map的使用。

了解有关地图的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

请使用简单的for of..循环,因为您的目的只是获取值并打印出来。

for(const transaction of transactions) {
  console.log(transaction.company_name || '');
  console.log(transaction.project_name || '');

  if(!transaction. tester_transaction)
    continue;

  console.log(transaction.tester_transaction.amount || '');
  console.log(transaction.tester_transaction.status || '');
}