0

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.

2
  • 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 Commented Aug 7, 2015 at 13:15
  • 1
    are you not meant to be comparing object['ID'] == ID? Commented Aug 7, 2015 at 13:22

7 Answers 7

4

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".

Sign up to request clarification or add additional context in comments.

7 Comments

@RickHitchcock Accuracy improved.
i've removed my comment for avoidance of confusion.. sorry about that
and for what it's worth, i was sort-of trying to refer to this
In my case is their a difference between single and double quotes
@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.
|
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"]);
    }

7 Comments

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 frameworks like jQuery are using the same strategy. Are you suggesting they are doing it wrong? Performance gain is always a gain ;)
@Shadowen, check High Performance JavaScript page 63. Written by Nicholas Zackas. If you are better than him, then i will agree ;)
You are just googling around. I'm arguing in behalf of an author :) I'll repeat my question. Are you better than him?
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.
|
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.

2 Comments

Why would he need to do that when object = locationID[i]; already do the same thing?
I meant for it to replace the loop he currently has, and it will return him an object for each iteration of the loop
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?

Comments

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;
  })
}

Comments

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
...

3 Comments

This seems unnecessarily complicated. And hard to understand, especially for any sort of beginner.
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..
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..
-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;
}

3 Comments

"meant for".. please source that assertion. for..in works just fine for arrays
" where the index order is important." - the OP's order is unimportant

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.