javascript - 获取对象内对象的值
问题描述
我返回一个带有嵌套对象的对象,如何获取嵌套对象的值。我想获取产品列表的值。
{
"status":"Processing","_id":"xx234455",
"products":[
{"_id":"5f81a7988289330","name":"ball ","price":70000,
}],
"returns":20000,"transaction_id":16855
}
解决方案
您可以使用.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。
推荐阅读
- c - 我可以通过同时在c中索引两个矩阵来将矩阵的值传递给另一个矩阵吗?
- transactions - 使用 api 或模块在莱特币测试网上发送原始交易(有 tx_hex)
- javascript - jQuery.ajax 不是函数 TypeError
- git - 'git pull' 直接 'fast-forword' 模式删除我的本地文件?
- javascript - 如何在 HTML 中显示类似开发网站的代码?
- r - 优化 bagging 和 boosting 分类器
- html - 使用 CSS 居中按钮集合
- r - 将新 data.frame 中的行添加到 ggplot2
- matlab - 从 CSV 文件中读取双引号中包含的数值
- node.js - 无法从领英验证访问令牌