Loop over divs and get data into json

I want to get the data of each div.p into a json format like one below so i can send it over an ajax request. My loop function only returns the data of the first div three time. Why ?

Required Format :
[ { ‘product_id’: ‘368’ ,‘quantity’: ‘3’ },
{ ‘product_id’: ‘356’ ,‘quantity’: ‘3’ }
]

JsFiddle : https://jsfiddle.net/gcomm/g4epk9qm/90/

My Code :

<div class="p">
  <div class="id">
    1
  </div>
  <div class="price">
    1500
  </div>
</div>
<div class="p">
  <div class="id">
    2
  </div>
  <div class="price">
    666
  </div>
</div>
<div class="p">
  <div class="id">
    3
  </div>
  <div class="price">
    5500
  </div>
</div>
$('.p').each(function(index, value) {
  console.log(
    JSON.stringify({
      aa: $('.id').text(),
      ab: $('.price').text(),
    }),
  );
});

This section of code is the focus of the issue.

      aa: $('.id').text(),
      ab: $('.price').text(),

Those are getting all id’s, and all prices, whereas you want them to be limited to each item that you are looping through.

You can achieve that by restricting the query to within only the element you are using in the loop.

      aa: $('.id', value).text(),
      ab: $('.price', value).text(),

For improved clarity of the code, I would also rename value to el instead.

$('.p').each(function(index, el) {
  console.log(
    JSON.stringify({
      aa: $('.id', el).text(),
      ab: $('.price', el).text(),
    }),
  );
});

Awesome it works. But can you explain the reason el works and not value ?

It comes down to expectations. With a variable called value, people are likely to expect it to be a number value, or at worst some kind of string value.

In your code it’s not a number or a string though, it’s an element. As such letting it remain as value can lead to easy confusions and mistakes. We should call it something that helps people to understand what it is. Because frequently those other people are us too.

Calling it el is a very generic way to let people know that it’s an element. More specific is better though, so if .p means a paragraph or price, we could easily rename el to para or price instead depending on what’s more relevant.