sjsc sjsc - 6 months ago 13
jQuery Question

Using jQuery, how do I select dynamic related data keys on an element and output them into an array?

For example, given this HTML:

<div class="playlist"
data-name1="Some Name 1"
data-value1="123"
data-name2="Some Name 2"
data-value2="456"
data-name3="Some Name 3"
data-value3="789"
></div>


I want to return an array of key/value pairs like so (using jQuery):

[{
"name": "Some Name 1",
"value": "123"
}, {
"name": "Some Name 2",
"value": "456"
}, {
"name": "Some Name 3",
"value": "789"
}]


Here is some pseudo code that I thought about but obviously doesn't work:

array = []
$(".playlist").attr("data-name-*, data-value-*").each(function(name, value){
array.push({"name": name, "value": value});
}
})
return array;


Any ideas?

Answer
var length_data = Object.keys($(".playlist").data()).length/2;

var data = []
for (i = 1; i <= length_data; i++) {
    data.push({"name" : $(".playlist").attr('data-name'+i), "value" : $(".playlist").attr('data-value'+i)} )
}

DEMO here

Update For prevent when u had more data :

var length_data = Object.keys($(".playlist").data()).length/2;

var data = []
for (i = 1; i <= length_data; i++) {
    if (typeof $(".playlist").attr('data-name'+i) == "undefined" || typeof $(".playlist").attr('data-value'+i) == "undefined" ) continue;
        data.push({"name" : $(".playlist").attr('data-name'+i), "value" : $(".playlist").attr('data-value'+i)} )

}

Demo update