0

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:

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

3 Answers 3

2

The code snippet is syntactically malformed (3 opening, 2 closing braces).

If that's just a typo, Object.keys(...) produces an array of property names. It would be set to ['amount', 'unit', 'quantity'].

Also, i should be initialized to 0.

What you intend is:

let i=0;
let keyPrice = fruit[i].prices.price; // Rename the variable!
console.log(keyPrice['amount']);
Sign up to request clarification or add additional context in comments.

Comments

1

it seems like you miss one curly brace } after null

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

and this for amount value

 fruit[0].prices.price.amount; 

Comments

0

You need a 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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.