0

I am creating a JavaScript array is the following manner:

var selectedColors= { 'Orange' : $("#Orange").val(), 'Light Blue' : $("#LightBlue").val(), 'Dark Red' : $("#DarkRed").val(), 'Dark Blue' : $("#DarkBlue").val()}; 

Then loop through each item to see which color was not selected, and then store them in another array:

var colorsNotSelected = []; $.each(selectedColors, function (key, value) { if (value.length == 0) colorsNotSelected.push({key:key}); }); 

Here I want to display the colors not selected, but doing it the following way display the keys: 0,1,2,3 instead of Orange, Light Blue, Dark Red, Dark Blue.

What am I doing wrong here?

if (colorsNotSelected.length > 0) $.each(colorsNotSelected, function (key) { alert(key) }); return false; 

Any help is much appreciated.

3
  • 2
    That is a Javascript Object, not a Javascript Array. FYI. Where is colorsNotSelected defined? Commented Nov 2, 2012 at 21:21
  • jsfiddle.net/6sp8s/2 <- Works fine as I see. Could you post what the value are Commented Nov 2, 2012 at 21:31
  • @KevinB miss type: added it above. selectedColors is a JS object, but why would that restrict me from accessing another array element? Commented Nov 2, 2012 at 21:55

2 Answers 2

1

The object and array would iterate the same in jQuery. It appears you need to use braces to keep that return false statement under check:

if (colorsNotSelected.length > 0) { $.each(colorsNotSelected, function (key) { alert(key) }); return false; } 

This is unnecessary:

colorsNotSelected.push({key:key}); 

Just do this:

colorsNotSelected.push(key); 

This is also assuming somewhere above your example code you have this:

var colorsNotSelected = []; 
Sign up to request clarification or add additional context in comments.

1 Comment

Still dont see the color names. 0,1,2,3 is displayed. Also, yes There is var colorsNotSelected = []; in my code
0

You might want to try a for / in loop instead:

for(var i in colorsNotSelected){ alert(i); } 

1 Comment

If you're going to use a for...in loop, use a if (colorsNotSelected.hasOwnProperty(i)) check to avoid iterating through the object's native/inherent properties.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.