-2

i have got the following JSON

[{
    "T1": "cost"
}, {
    "T6": "Service Tax"
}, {
    "T3": "VAT"
}, {
    "T4": "OtherTax2"
}, {
    "T5": "OtherTax1"
}, {
    "T2": "Discount"
}, {
    "T7": "Service Charge"
}];

and i am able to retrive T1 value using

var t1value = myjson[0].T1;

But when i am trying to retrive T2 value why its is giving me undefined

http://jsfiddle.net/mwv6r0df/4/

Could you please tell me how can i retrieve all the values

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • 2
    That's an array of objects. Each object has only 1 property. Come on, this is pretty basic. – Ram Dec 28 '15 at 10:01
  • myjson[5].T2; "an array" – Vanojx1 Dec 28 '15 at 10:02
  • Possible duplicate of [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) –  Dec 28 '15 at 10:05
  • To retrieve all the values just use a `for` loop. – Sam Dec 28 '15 at 10:05
  • As I see that is an array of objects and they have different properties. If there is no convention in property name, I think it's hard to retrieve all the values. – HieuHT Dec 28 '15 at 10:32

2 Answers2

2

That's because first index has no property name T2.

First Index has only one property name T1.

5th index has property name T2

console.log(myjson[5].T2);

If your object design is

[{
    "T1": "cost",
    "T6": "Service Tax",
    "T3": "VAT",
    "T4": "OtherTax2",
    "T5": "OtherTax1",
    "T2": "Discount",
    "T7": "Service Charge"
}];

Then your approach is correct.

console.log(myjson[0].T2);

But In your design every index has different property.

JSFIDDLE

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
0

Your JSON

console.log(myjson.toString());

OUTPUT

[object Object],[object Object],[object Object],...,[object Object]
       ↑              ↑                ↑                   ↑
idx = (1)            (2)              (3)                 (n)  

If way this

var myjson = 
[{
    "T1": "cost", 
    "T6": "Service Tax",
    "T3": "VAT",
    "T4": "OtherTax2",
    "T5": "OtherTax1",
    "T2": "Discount",
    "T7": "Service Charge"
}];

OUTPUT

[object Object]
Gurkan Yesilyurt
  • 2,635
  • 2
  • 20
  • 21