2

I have such an array as below;

//var tt is from console.log
var tt =[
         {"price":50,"quantity":1,"sku":1},
         {"price":70,"quantity":5,"sku":2}
        ];

NB: var tt is an array I get when I do console.log; of which when I store it as above to var tt, it works normally.

I have tried the following;

 console.log(tt.price);//this give me 'undefined'
 console.log(tt['price'];//this also gives me 'undefined'

Anyone who knows how to access values from such an array?

3 Answers 3

2

You have to choose an element from the array before accessing the price member.

console.log(tt[0].price);     // 50
console.log(tt[1]['price']);  // 70
Sign up to request clarification or add additional context in comments.

3 Comments

Hello @Willis Blackburn, strangely, that too returns 'undefined'
Then the code you're running isn't what you've posted in the question. I ran it in the browser console and it worked. Provide a link to JSFiddle or something like that and I'll take a look.
The value for var tt I copy-pasted from console, because if indeed you run as it is, it will work with your solution, am guessing the values from the console is treated differently when stored in a variable, trying to figure out the mystery behind it
1

It is an array of objects, so you have to use the array syntax to access the object and then you can use the attribute name.

tt[0].price

This is what you want.

3 Comments

var tt is an array I get when I do console.log; of which when I store it as above to var tt, it works as you have suggested, does it need to be converted to something first?
No, that way is ok accordingly to JSON notation.
I also thought I was doing something wrong, found out values displayed in console cant be somehow treated as in the case of var tt, though they seem to hold same arrays. Still trying to figure out what is happening here
0

console.log() is actually a function in js, which does not return anything. So if you say you are assigning a consoloe.log() to var tt then you are actually getting undefined in the variable because the function returns nothing.

var tt = console.log([
         {"price":50,"quantity":1,"sku":1},
         {"price":70,"quantity":5,"sku":2}
])
//therefore
console.log(tt) or 
console.log(tt[0]['price'])
//will give you undefined.

if you are doing this

         //first
var tt = console.log([
         {"price":50,"quantity":1,"sku":1},
         {"price":70,"quantity":5,"sku":2}
        ])
        //second  
        console.log(tt)

Then it will first print the array from the first console.log and then print undefined from the second. var tt will still have no value assigned to it and will give you undefined.

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.