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

问题描述 投票:0回答:3

我进行了搜索,但找不到答案;我认为它很简单,但我做不到。尝试在此处获取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
javascript arrays node.js key-value
3个回答
2
投票

代码段在语法上不正确(3个大括号,2个大括号)。

如果只是一个错字,Object.keys(...)会生成一个属性names的数组。它将设置为['amount', 'unit', 'quantity']

此外,i应该初始化为0

您打算做什么:

let i=0;
let keyPrice = fruit[i].prices.price; // Rename the variable!
console.log(keyPrice['amount']);

1
投票

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

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

以及此金额值

 fruit[0].prices.price.amount; 

0
投票

您需要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);
});
© www.soinside.com 2019 - 2024. All rights reserved.