5

I read a HTML element's property using JavaScript like this:

<table data-option="pageSize:10, pageNumber:1, rowNumber:true"></table>

I will have a string like this:

attrs="pageSize:10, pageNumber:1, rowNumber:true";

I have a key and value JavaScript object like this:

obj={pageSize:12, pageNumber:1, rowNumber:true}

I want to convert my attrs to object like obj.

adeneo
  • 312,895
  • 29
  • 395
  • 388

2 Answers2

0

You could iterate and create the object yourself

var attr = $('table').data('option');
var obj  = {};

$.each(attr.split(','), function(index, item) {
    var parts = $.map(item.split(':'), function(part) {
        part = $.trim(part);
        if ( +part == part ) return +part
        else if ( part === 'true' ) return true
        else if ( part === 'false') return false
        else return part;
    });
    obj[parts[0]] = parts[1];
});

var attr = $('table').data('option');
var obj  = {};

$.each(attr.split(','), function(index, item) {
 var parts = $.map(item.split(':'), function(part) {
     part = $.trim(part);
     if ( +part == part ) return +part
        else if ( part === 'true' ) return true
        else if ( part === 'false') return false
        else return part;
 });
    obj[parts[0]] = parts[1];
});

document.body.innerHTML = '<pre>' + JSON.stringify(obj, null, 4) + '</pre>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table data-option="pageSize:10, pageNumber:1, rowNumber:true"></table>
adeneo
  • 312,895
  • 29
  • 395
  • 388
-1

Option 1.

Store an entire json-encoded string.

Option 2.

To convert that from string to an object with JSON.parse you'll need double quotes.

Using a regex to add double quotes taken from here, we get the desired result:

attrs = ("{" + attrs + "}").replace(/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/g,'$1"$3":');
var obj = JSON.parse(attrs);

UPD:

As mentioned by epascarello, if you have unquoted string values there like name: Jack, this approach would obviously fail. But if you're putting raw strings there, mind that they might contain commas or spaces or whatever, so you'd better quote them

Community
  • 1
  • 1
Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56