1

THis is going to sound like a stupid question but here it goes. I have a js array formatted like so

 var locationID = [
              { ID: "ID1", location: "location1" },
              { ID: "ID2", location: "location2" },
              { ID: "ID3", location: "location3" },
   ];

I am trying to loop through the array

for(i = 0; i < locationID.length;i++){
   var object = locationID[i];
}

I want to get both elements from the inner array so the ID and location. would I do this by object[0] or object["ID"] for example.

Also is there a more efficient way to do what I need to do like a for each loop or something along those lines.

  • 1
    object["ID"] and object["location"] should work fine, can´t really be more efficient than that, just other ways of doing the same, after all you need to traverse all – juvian Aug 07 '15 at 13:15
  • 1
    are you not meant to be comparing `object['ID'] == ID`? – billyonecan Aug 07 '15 at 13:22

7 Answers7

5

Use object.ID or object['ID'].

Objects {} in JavaScript are associative, or named arrays. (Also known as a map in many languages. They are indexed by strings (in this case).

Arrays [], are indexed by integral numbers, starting from 0 and counting up to n-1, where n is the length of the array.

If you want to programmatically go through all the (key, value) pairs in each object, you can use this method.

Quotations (String Literals)

To reiterate my comment below about single and double quotes:

If you're talking about inside the [], no [,they're not important]. JavaScript treats single quotes and double quotes pretty much the same. Both of them denote string literals. Interestingly, you can use single quotes inside double quotes or vice-versa: "I wanted to say 'Hello world!'" would be a (single) valid string, but so would 'But I accidentally said "Goodbye".

Community
  • 1
  • 1
Shadowen
  • 838
  • 5
  • 14
  • 1
    @RickHitchcock Accuracy improved. – Shadowen Aug 07 '15 at 13:22
  • i've removed my comment for avoidance of confusion.. sorry about that – ddavison Aug 07 '15 at 13:22
  • and for what it's worth, i was sort-of trying to refer to [this](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets#answer-4968448) – ddavison Aug 07 '15 at 13:25
  • In my case is their a difference between single and double quotes – James Scroll Aug 07 '15 at 13:26
  • @sircapsalot This is only in the case of properties with special characters (invalid identifiers). You should avoid these characters in "regular" properties, such as those you define yourself. Keep the usage of `Objects` and `associative arrays` logically separated. – Shadowen Aug 07 '15 at 13:31
  • indeed.. thanks for your input .. i'm sure @JamesScroll will find your information useful – ddavison Aug 07 '15 at 13:39
  • @JamesScroll If you're talking about inside the `[]`, no. JavaScript treats [single quotes and double quotes pretty much the same](http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript). Both of them denote string literals. Interestingly, you can use single quotes inside double quotes or vice-versa: `"I wanted to say 'Hello world!'"` would be a valid string, but so would `'But I accidentally said "Goodbye"`. – Shadowen Aug 07 '15 at 13:50
0

This is an optimized loop based from the book of Nicholas Zackas (YAHOO performance chief). I am performing a cached array length to prevent re-evaluation of array length on every iteration of the loop. Please check jsperf.com. Also, native loop is always faster than method based loops jQuery.each and Array.prototype.forEach. This is also supported on browsers below ie8

    var currentItem,
        locationInfo = [
          { ID: "ID1", location: "location1" },
          { ID: "ID2", location: "location2" },
          { ID: "ID3", location: "location3" },
        ];

    for (var i = 0, len = locationInfo.length; i < len; i++) {
        currentItem = locationInfo[i];

        console.log(currentItem.ID);//I prefer this because it shrinks down the size of the js file
        console.log(currentItem["ID"]);
    }
Allan Chua
  • 9,305
  • 9
  • 41
  • 61
  • While it is true that you are "optimizing" the loop, this kind of micro-optimization tends to clutter the code, confuse programmers, and gives negligible performance benefits. Furthermore, `[].length` is a `Number`, not a `Function`, so I fail to see how caching the value will increase performance. Finally, shrinking the JavaScript by 3 characters using the `.` notation rather than `[]` is beyond unnecessary. At this point it'd be better to minify your code. – Shadowen Aug 07 '15 at 13:29
  • @Shadowen frameworks like jQuery are using the same strategy. Are you suggesting they are doing it wrong? Performance gain is always a gain ;) – Allan Chua Aug 07 '15 at 13:34
  • @Shadowen, check High Performance JavaScript page 63. Written by Nicholas Zackas. If you are better than him, then i will agree ;) – Allan Chua Aug 07 '15 at 13:35
  • You are just googling around. I'm arguing in behalf of an author :) I'll repeat my question. Are you better than him? – Allan Chua Aug 07 '15 at 13:43
  • I'm using jsperf as experimental evidence. After all, what we care about is real-world performance, not what authors say is best. Also, Google is a great source of information. Sort of like [StackOverflow](http://stackoverflow.com/questions/5752906/is-reading-the-length-property-of-an-array-really-that-expensive-an-operation). – Shadowen Aug 07 '15 at 13:46
  • @Shadowen, do you even understand the results of the test? it says that Array.map is 98% is slower :D – Allan Chua Aug 07 '15 at 13:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/85432/discussion-between-shadowen-and-allan-chua). – Shadowen Aug 07 '15 at 15:19
0

what you have already will return each of the objects in the JSON as you run the loop. What you need is something like

for(i = 0; i < locationID.length;i++){
   var object = {locationID[i].ID, locationID[i].location};
}

Remember properties of objects are accessed by their keys since they are key-value pairs.

Huan Zhang
  • 1,095
  • 8
  • 13
  • 2
    Why would he need to do that when `object = locationID[i];` already do the same thing? – Shryme Aug 07 '15 at 13:21
  • I meant for it to replace the loop he currently has, and it will return him an object for each iteration of the loop – Huan Zhang Aug 07 '15 at 13:29
0

You can use the forEach method, which make your code more cleaner.

See forEach

locationID.forEach(function(elm){
  //Here, elm is my current object
  var data = elm;
  console.log(data.ID):
  console.log(data.location);
});

EDIT : Then for your second question, you should filter and map methods.

function findNamebyID(id){
  //Filter by id and map the data to location
  return locationID.filter(function(elm){
    return elm.ID === id;
  }).map(function(elm){
    return elm.location;
  })
}
Paul Boutes
  • 3,285
  • 2
  • 19
  • 22
0

For loops are going to be your best bet as far as speed, here's how you'd do it with forEach (IE 9+)

locationID.forEach(function(location, i){
    console.log(location['ID'])
    console.log(location['location'])
});

jQuery make's it a little easier but runs slower

$.each(array, function(i, item){

});

http://jsperf.com/for-vs-foreach/75

Also here a useful link: For-each over an array in JavaScript?

Community
  • 1
  • 1
Mike
  • 189
  • 1
  • 2
  • 18
0

Something as:

var location = locationID.reduce(function(ob, cur) {
ob[cur.ID] = cur.location;
return ob;
}, {});

The result you get is:

Object {ID1: "location1", ID2: "location2", ID3: "location3"}

Meaning you can do:

location.ID1 // location1
location.ID2 // location2
...
gor181
  • 1,988
  • 1
  • 14
  • 12
  • This seems unnecessarily complicated. And hard to understand, especially for any sort of beginner. – Shadowen Aug 07 '15 at 13:33
  • People should check reduce as it's the heart of all other functions we daily use, as map, foreach and similar.. It's quite simpler than using for.. – gor181 Aug 07 '15 at 13:34
  • I would think you want `map` for your approach, but you might want to read the original question again. I'm not sure if you're solving a completely different problem from what the author intended.. – Shadowen Aug 07 '15 at 14:20
-1

an alternative to your loop, would be to use the JavaScript for (.. in ..) since you aren't really using the iterator; it just adds fluff

for(i = 0; i < locationID.length;i++){
   var object = locationID[i];
}

could be written as:

for (item in locationID) {
  var object = item;
}
ddavison
  • 28,221
  • 15
  • 85
  • 110