0
   var obj = [];
  $("tr[class*='row_']").each(function () {
   var coord = ($(this).find("td:eq(1)").text().match(/\d{1,3}\|\d{1,3}/g)).toString();


    //alert($(this).find("td:eq(0)").text())

   if (obj[coord]) {obj[coord]++;}
   else { obj.push({coord : 1 }) }

   })

    alert(JSON.stringify(obj));

My output:

     [{"coord":1},{"coord":1},{"coord":1},{"coord":1},{"coord":1},{"coord":1}]

When it should be:

 523|546 : 3,
 521|424 : 3

How wan I push "name" : 1 when coord is my name?

2
  • where are those numbers coming from? can you post us the table? Commented Feb 5, 2014 at 9:37
  • The table looks like this : 005 (523|426) C45 x 3 and [166 Flora] (521|424) C45 x 3. My regex is correct since I already tested that, the problem is pushing a coordinate (523|426 for example) with the number 1 in an object. (So if the coordinate isnt in the object yet, push coord : 1, else 1 + 1 :) Commented Feb 5, 2014 at 9:42

1 Answer 1

3

You're using an array in your code var obj = []. If you want an object you need to do this var obj = {}.

Then later on you use obj.push({coord : 1 }). That only works for arrays. For objects you can just do this obj[coord] = 1

var obj = {};
$("tr[class*='row_']").each(function () {
    var coord = ($(this).find("td:eq(1)").text().match(/\d{1,3}\|\d{1,3}/g)).toString();
    //alert($(this).find("td:eq(0)").text())

    if (obj[coord]) {
       obj[coord]++;
    }  
    else { 
      obj[coord] = 1; 
    }
});

alert(JSON.stringify(obj));
Sign up to request clarification or add additional context in comments.

6 Comments

That doensn't work, the object is empty at the start, so you can't just do that because you have to add the key (coord) and the initial value (1) first.
Let me add a simple jsFiddle. Give me a few minutes.
Never mind, that was a stupid mistake of mine, lol. Thank you for your answer, accepted it :)
I mean I'll accept in three minutes, can't right now. :)
Yeah no problem. Since I already completed the jsFiddle. Here is the link jsfiddle.net/daGEJ
|

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.