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

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