从数组的数组中的数组中获取元素的值



我搜索了一下,但找不到答案;我认为这很容易,但我做不好。尝试在此处获取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']);

在空之后似乎错过了一个大括号}

let fruit = [
{"prices":
{"price":
{"amount":4.97,"unit":"ea","quantity":1}
,"wasPrice":null}
}
]

这是金额值

fruit[0].prices.price.amount; 

您需要一个dig函数:

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);
});

最新更新