首页 > 解决方案 > 获取对象内对象的值

问题描述

我返回一个带有嵌套对象的对象,如何获取嵌套对象的值。我想获取产品列表的值。

{
"status":"Processing","_id":"xx234455",
"products":[
{"_id":"5f81a7988289330","name":"ball ","price":70000,
 }],
"returns":20000,"transaction_id":16855
}

标签: javascript

解决方案


您可以使用.forEach()ofproducts数组对其进行迭代,也可以通过索引访问元素:

const data = {"status":"Processing","_id":"xx234455","products":[{"_id":"5f81a7988289330","name":"ball ","price":70000,}],"returns":20000,"transaction_id":16855}

// iterate
data.products.forEach(e => console.log(e._id))

// by index
console.log(data.products[0]._id)

从以下文档中查看.forEach()

forEach() 方法为每个数组元素执行一次提供的函数。

另请参阅使用索引位置部分访问数组项的数组文档。


在标签建议的React.map()中,也可以使用as:

return <>
   {
      data && data.products &&
      data.products.map((e, i) => <span key={i}>{e._id}</span>)
   }
</>

特别是对于数组的使用,我建议阅读React 文档中的Lists and Keys


推荐阅读