简体   繁体   English

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

[英]Get the value of an element from an array in an array of array

I searched but couldnt find the answer to this;我搜索但找不到答案; I assume its pretty easy but I cant get it right.我认为它很容易,但我无法做到。 Trying to get the value of amount here:试图在这里获得amount的价值:

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

I have loop and I tried something like this;我有循环,我尝试过这样的事情; but didnt work:但没有用:

keyPrice = Object.keys(fruit[i].prices.price); 
console.log(keyPrice['amount'])
//this is giving me undefined result

The code snippet is syntactically malformed (3 opening, 2 closing braces).代码片段在语法上是错误的(3 个左大括号,2 个右大括号)。

If that's just a typo, Object.keys(...) produces an array of property names .如果这只是一个错字, Object.keys(...)会生成一个属性名称数组。 It would be set to ['amount', 'unit', 'quantity'] .它将被设置为['amount', 'unit', 'quantity']

Also, i should be initialized to 0 .另外, i应该被初始化为0

What you intend is:你的意图是:

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

it seems like you miss one curly brace } after null好像你在 null 之后错过了一个花括号}

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

and this for amount value这是金额值

 fruit[0].prices.price.amount; 

You need a dig function:你需要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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM