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

2
  • So the result you want is an array of objects, correct? Commented Apr 12, 2019 at 13:41
  • I have created a working example of what I think you are after here: jsfiddle.net/ft67g42d Commented Apr 12, 2019 at 13:54

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you but what i want is instead of element.id can i have something like element.$(this).val() as the object
@TapiwaTakaindisa Not sure what you mean. Can you give me an example of exactly what you want the resulting object to look like?
1
var dd = {};
dd.test = 5;

or

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.