0

when trying to run the following code:

var pvals = new Array(); pvals = "[" + $("#upcheck").val() + "]"; pvals = $.parseJSON(pvals); pvals = pvals.sort(function(a,b) { return parseFloat(a.id) - parseFloat(b.id) } ); for (var i = 0; pvals.length; i++) { if (i == 0) { //do something } else { if (pvals[i].id == pvals[i - 1].id) { //do something } else { //do something else } } } 

Firebug within Firefox shows the following message "TypeError: pvals[(i - 1)] is undefined" Can anyone please help? I have defined pvals as an array.

Thanks

Ryan

3
  • i am getting the json from a textbox, i have updated the code above to what im using and this is the json in the textbox: {"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"} Commented May 1, 2014 at 20:06
  • Please check my the last part of my response. You're running out of bounds when i == 4. Commented May 1, 2014 at 20:10
  • it still doesnt like if (pvals[i].id == pvals[i - 1].id) Commented May 1, 2014 at 20:14

3 Answers 3

1

This should work:

pvals = '[{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]'; 

Also:

for (var i = 0; i<pvals.length; i++) { // if not loop doesnt stop 
Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't make a bit of sense to write json as a string, then immediately parse it.

Rather than using JavaScript Object Notation as a string, just notate the object in javascript.

pvals = [{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]; 

Comments

0

The way you define pvals doesn't work. You need to escape the quotes.

pvals = '[{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]'; 

Alternatively, just use it as an array, and forget the JSON.parse():

pvals = [{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]; 

Also, your for loop doesn't end unless pvals.length becomes 0 or false. You should change that line to for (var i = 0; i < pvals.length; i++) {, which will fix your undefined error since you were trying to access an array index that was out of bounds.

Edit: The last statement still holds true based on OP's edited question.

4 Comments

No; use an array literal.
We're not sure if the data he's actually getting is in the form of JSON, or a JSON string.
What's the difference?
Haha, fubar'ed there.. I meant "Javascript Object, or a JSON string". Thanks @JoeFrambach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.