0

Following is my JSON format,

{
"records": [
{
"ID": "4",
"TYPE": "landscape",
"FIMAGE": "viewveni.jpg",
"COUNT": "4444"
}
],
"pagination": {
"count": 1,
"page": 1,
"limit": 10,
"totalpages": 1
}
}

I am trying really hard to fetch the Second element of First element, i.e. records.TYPE, but i can not use the index name TYPE.

I know records[0][1] won't work and i am really out of options now.

Edit:

I know I can fetch data as records[0].TYPE but I can't use TYPE as plain text, how ever if it's a variable then it's ok, ie. Something like records[0].cat where cat = 'TYPE'

Mercurial
  • 3,615
  • 5
  • 27
  • 52
  • You can try `let [key, val] = Object.entries(records[0])[1]` but results may be inconsistent (see Nikhil's answer below) – Phil Oct 18 '19 at 00:14
  • Is it possible to get the value inline? I know there are hundreds of ways to do this, but I want short inline solution, kindly check the updated questions. – Mercurial Oct 18 '19 at 00:20

1 Answers1

2

Use records[0].TYPE or records[0]["TYPE"].

Refer MDN documentation on Property Accessors for more info.

I am trying really hard to fetch the Second element of First element

TYPE is not the second element of records array element. Object properties are not ordered.

var data = { "records": [{ "ID": "4", "TYPE": "landscape", "FIMAGE": "viewveni.jpg", "COUNT": "4444" }], "pagination": { "count": 1, "page": 1, "limit": 10, "totalpages": 1 } };

var result = data.records[0].TYPE;

console.log(result);

Object.values(data.records[0])[1] will give inconsistent results because object properties are not ordered.

var data = { "records": [{ "ID": "4", "TYPE": "landscape", "FIMAGE": "viewveni.jpg", "COUNT": "4444" }], "pagination": { "count": 1, "page": 1, "limit": 10, "totalpages": 1 } };

console.log(Object.values(data.records[0])[1]); 

If TYPE value will be stored in a variable, then you can use bracket notation to access the value.

var data = { "records": [{ "ID": "4", "TYPE": "landscape", "FIMAGE": "viewveni.jpg", "COUNT": "4444" }], "pagination": { "count": 1, "page": 1, "limit": 10, "totalpages": 1 } };

let prop = "TYPE";

console.log(data.records[0][prop]);
Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • ` i can not use the index name TYPE`, sorry! – Mercurial Oct 18 '19 at 00:11
  • 2
    `TYPE` is not an index, it is a property of the object. There is no second element in objects because object properties are not ordered. You can use `Object.values(data.records[0])[1]` but you'll get different output each time, so it shouldn't be used. – Nikhil Oct 18 '19 at 00:16
  • Are JavaScript variable indexes are case sensitive? – Mercurial Oct 18 '19 at 00:30
  • 1
    @Mercurial - Yes, they are case sensitive. – Nikhil Oct 18 '19 at 00:32