Reputation: 105
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?
Upvotes: 2
Views: 2892
Reputation: 3
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.
Upvotes: 0
Reputation: 1366
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.
Upvotes: 1
Reputation: 8204
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
Upvotes: 2