[英]Get the value of an element from an array in an array of array
我搜索但找不到答案; 我認為它很容易,但我無法做到。 試圖在這里獲得amount
的價值:
let fruit = [
{"prices":{"price":{"amount":4.97,"unit":"ea","quantity":1},"wasPrice":null}
]
我有循環,我嘗試過這樣的事情; 但沒有用:
keyPrice = Object.keys(fruit[i].prices.price);
console.log(keyPrice['amount'])
//this is giving me undefined result
代碼片段在語法上是錯誤的(3 個左大括號,2 個右大括號)。
如果這只是一個錯字, Object.keys(...)
會生成一個屬性名稱數組。 它將被設置為['amount', 'unit', 'quantity']
。
另外, i
應該被初始化為0
。
你的意圖是:
let i=0;
let keyPrice = fruit[i].prices.price; // Rename the variable!
console.log(keyPrice['amount']);
好像你在 null 之后錯過了一個花括號}
let fruit = [
{"prices":
{"price":
{"amount":4.97,"unit":"ea","quantity":1}
,"wasPrice":null}
}
]
這是金額值
fruit[0].prices.price.amount;
你需要dig
function:
function dig(obj, func){ let v; if(obj instanceof Array){ for(let i=0,l=obj.length; i<l; i++){ v = obj[i]; if(typeof v === 'object'){ dig(v, func); } else{ func(v, i, obj); } } } else{ for(let i in obj){ v = obj[i]; if(typeof v === 'object'){ dig(v, func); } else{ func(v, i, obj); } } } } let fruit = [ { prices:{ price:{ amount:4.97, unit:'ea', quantity:1 }, wasPrice:null } } ]; dig(fruit, (v, i, obj)=>{ if(i === 'amount')console.log(v); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.