1

I want to create a JSON object entirely from the attributes of HTML elements that share the same class so that the key is say the data attribute and value is the id.

I've tried the code below :

$("#searchBtn").click(function() {
  var map = [];
  $(".searchTextField").each(function() {
    var fieldName = $(this).attr('data-field-name')
    map.push({
      $(this).attr('data-field-name'): $(this).val()
    })
    alert(map);
  });
})

what I want to achieve is to have some like

{
  "id" : 1,
  "page" : 5
} 

but id and page must be dynamic i.e the text id is taken from an tribute of an HTML element

Eddie
  • 26,593
  • 6
  • 36
  • 58

2 Answers2

2
$("#searchBtn").click(function () {
    var map = [];

    $(".searchTextField").each(function() {
        var element = {}; 

        element.id = $(this).data('field-name');
        element.page = $(this).val();

        map.push(element);
    });

    alert(map);
});
sdesapio
  • 138
  • 1
  • 9
  • thank you but what i want is instead of element.id can i have something like element.$(this).val() as the object – Tapiwa Takaindisa Apr 12 '19 at 14:06
  • @TapiwaTakaindisa Not sure what you mean. Can you give me an example of exactly what you want the resulting object to look like? – sdesapio Apr 12 '19 at 14:15
1
var dd = {};
dd.test = 5;

or

var dd = {};
dd['test'] = 5;