0

I am using the following code to look for a specific value id in javascript object. I am getting duplicate objects.

This is the javascript code I am using:

$('.seat').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

   //SeatId is 1
    var categoryArray = jsonData;
    var id = $(this).attr('id');
    var ticketData, seatLocation;
    for (var i = 0; i < categoryArray.length; i++) {
            var category = categoryArray[i];
            for (var j = 0; j < category.assignments.length; j++) {
                if (category.assignments[j].seatId == id) {
                    ticketData = category;
                    seatLocation = category.assignments[j];
                }
            }
        }

    console.log(ticketData);
    console.log(seatLocation);

});

This is how the objecs look like after being parsed:

enter image description here

And this is how the data is being printed: enter image description here

What am I doing wrong?

Afshin
  • 2,427
  • 5
  • 36
  • 56
  • 4
    `This is my JSON structure` - no it isn't ... JSON is a string format, that's just a plain ol' javascript object – Jaromanda X May 16 '17 at 04:35
  • _"Everything is OK except the duplicate data I am getting"_ Which data are you referencing? What is expected result? – guest271314 May 16 '17 at 04:40
  • am I correct now? I edited my question. – Afshin May 16 '17 at 04:43
  • 1
    You're using the same index `i` to access elements in both arrays `categoryArray[i].assignments[i]` you should probably use an inner loop to access the elements inside the `assignments` array. – Titus May 16 '17 at 04:45
  • @Titus I did. Still the same problem! Check out my code – Afshin May 16 '17 at 04:49
  • Since you're `console.log`ing the results outside the loops the problem seems to be that you're click callback function is called more then once. Make sure you haven't added `purchase.js` more then once to the page. – Titus May 16 '17 at 04:53
  • 1
    It does appear your callback function is triggering more than once, take a look at this related question: http://stackoverflow.com/questions/14969960/jquery-click-events-firing-multiple-times – Omn May 16 '17 at 05:00

1 Answers1

0

Try this way:

$('.seat').on('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
                        var ticketData = [];
                    var seatLocation = [];
    //SeatId is 1
    var categoryArray = jsonData;
    var id = $(this).attr('id');
    $.each(categoryArray, function (i, cat) {
        $.each(cat.assignments, function (j, ass) {
            if (ass.seatId == id) {
                    ticketData = cat;
                    seatLocation = ass;
                }
            });
    });

    console.log(ticketData);
    console.log(seatLocation);

});
Govind Samrow
  • 9,981
  • 13
  • 53
  • 90