0

i have this object called defined in my code as rates.rates:

{ AUD="1.4553",  BGN="1.9558",  BRL="3.5256"}

and i have the following $.each loop:

$.each( rates.rates, function( index, value ){

  console.log(index);

});

I've been trying without success to also console.log the next or the previous index (if they exist of course). Any help is really appreciated.

9
  • 1
    You can save the previous index in a variable. There's no way to get the next index. Commented Oct 13, 2016 at 9:06
  • 1
    Except that's poorly explained, why would you save the net index, for wich purpose? let us know, there is many possible answers depending on your final goal. Commented Oct 13, 2016 at 9:07
  • You can check the index against the total number of elements and 0 to see if they exists. Commented Oct 13, 2016 at 9:11
  • Your object syntax is wrong. It's key: value, not key=value Commented Oct 13, 2016 at 9:12
  • set a counter to 0 before the each, and then increment on each iteration of the each loop. This gives a pseudo-index for your loop. Commented Oct 13, 2016 at 9:12

3 Answers 3

2

Instead of iterating over the object, get its keys as an array and iterate over that. Then you can add and subtract from the array index.

var keys = Object.keys(rates.rates);
$.each(keys, function(index, key) {
    var prevkey = index > 0 ? keys[index-1] : null;
    var nextkey = index < keys.length-1 ? keys[index+1] : null;
    console.log(prevkey, key, nextkey);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Best answer at the moment, just because it's what the OP's was asking for.
0

JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.

But there's a way for you to do what you want.You can do it like this.

var keys=Object.keys(rates.rates);

for(vari=0; i<keys.length;i++)
{       
    console.log(i);  
}

Comments

0

You can get the next or prev with modulo. With this you can make a loop automatically.

Please try below:

rates={
    rates:{ "AUD":"1.4553",  "BGN":"1.9558",  "BRL":"3.5256"}
  };
var keys = Object.keys(rates.rates);
$.each(keys, function(index, key) {
    if(index == 0){index=keys.length};
    var prevkey = (index-1) % keys.length; 
    var nextkey = (index+1) % keys.length; 
    console.log(prevkey, key, nextkey);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.