1

I'm trying to serialize sortable list using data-id attribute instead of just id.

This is my code:

var obj = $('.sortable li').map(function() {
    return 'id=' + $(this).data("id");
}).get();

JSON.stringify(obj)

which returns:

["id=1", "id=2", "id=3"]

what I need is to return:

[{"id":1},{"id":2},{"id":3}]

Here is the html part:

<ul class="sortable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3</li>
  <li data-id="4">Item 4</li>
  <li data-id="5">Item 5</li>
</ul>

2 Answers 2

3

var id = [];
$('.sortable li').each(function() {
  id.push({
    id: $(this).data('id')
  });
})

console.log(JSON.stringify(id))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="sortable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3</li>
  <li data-id="4">Item 4</li>
  <li data-id="5">Item 5</li>
</ul>

Check this using .each() and .push()

Sign up to request clarification or add additional context in comments.

Comments

2

You can achieve this by using map method itself.

var obj = $('.sortable li').map(function() {
 return {
   id: $(this).data("id")
 };
}).get();

JSON.stringify(obj);

1 Comment

Thanks I prefer map method instead of each.

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.