1

I have the following very massive array:

var arrayBig = {"count":31,"items":{"76":{"title":"office1","address":"<p><strong>London<\/strong><\/p>\r\n<p>Baker Str.<\/p>\r\n<p>Web site: <a href=\"http:\/\/example.org\">http:\/\/example.org<\/a><\/p>"},"57":{"title":....... etc. }....

And all I need is to get the first number in 'items', e.g. 76, with jQuery.

zerkms
  • 230,357
  • 57
  • 408
  • 498
gogol75
  • 63
  • 3
  • 1
    It's not an array. To access object attributes use `.` or `[]` operators. – zerkms Dec 23 '14 at 08:52
  • You can get it with [object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method of JS. – Alexander Arutinyants Dec 23 '14 at 08:52
  • 1
    @Alexander Arutinyants: it worth mentioning that properties of objects are not ordered. And the standard **DOES NOT** guarantee any order. So technically - it's impossible to retrieve the **first** attribute of an object. – zerkms Dec 23 '14 at 08:53
  • Thanks. I know how to get 'title' or 'address'. But don't know how to get the number in the beginning - it has no name. – gogol75 Dec 23 '14 at 08:54
  • Ok. I see, first you wanna do search by any field, then get the number? – Alexander Arutinyants Dec 23 '14 at 08:55
  • I want to make a loop. And get all the values - as well as 'title' and 'address', but also the id. – gogol75 Dec 23 '14 at 08:57
  • for(key in arrayBig.items){ if(arrayBig.items[key].title === "office1"){ //use this condition to search console.log(key); break; //important to not to scan all array } }; othervise just loop and console log key, arrayBig.items[key].title and arrayBig.items[key].addr – Alexander Arutinyants Dec 23 '14 at 09:03
  • I made a jsfiddle for you where you can play with all this: http://jsfiddle.net/elennaro/7ht9prh0/ – Alexander Arutinyants Dec 23 '14 at 09:09

2 Answers2

1

Just try with:

var firstKey = Object.keys(arrayBig.items)[0];
arrayBig.items[firstKey]
hsz
  • 136,835
  • 55
  • 236
  • 297
  • 1
    Order of properties **IS NOT DEFINED** and **IS NOT GUARANTEED**. – zerkms Dec 23 '14 at 08:54
  • @zerkms it returns first key anyway. If it should be the lowest key in group, array of keys should be sorted. – hsz Dec 23 '14 at 08:57
  • "it returns first key anyway" --- it returns for this particular run for this particular version of ECMAScript implementation. Nothing prevents the JS VM to change the object layout for memory optimization purposes. It's like crazy to rely on something that is not standardized and is not guaranteed. – zerkms Dec 23 '14 at 08:58
1

try

var arrayObj = [];
    $.each(arrayBig.items, function(key, val) {

           arrayObj.push(key);

        });​

alert(arrayObj[0]);
Rahul
  • 690
  • 1
  • 6
  • 24