[英]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.