user1679941
user1679941

Reputation:

Does javascript have a shorthand way of setting up fields in an object?

I am using the following:

var link = {};
link.action = $link.attr('data-action') || '';
link.dialogType = $link.attr('data-dialogType') || '';
link.params = $link.attr('data-params') || '';
link.title = $link.attr('title') || '';
link.viewURL = $link.attr('data-href') || '';
link.entity = $link.attr('data-entity') || '';
link.row = $link.attr('data-row');

But is there a better way to do this?

Upvotes: 1

Views: 77

Answers (2)

Ram
Ram

Reputation: 144689

You can use dataset property.

Allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

var elm = $link[0], data = elm.dataset, link = { title: elm.title };
for (var i in data) link[i] = data[i]

http://jsfiddle.net/AdzE3/

Upvotes: 1

webdeveloper
webdeveloper

Reputation: 17288

Try this:

var link = {
   action : $link.data('action') || '',
   dialogType : $link.data('dialogType') || '',
   params : $link.data('params') || '', 
   title : $link.attr('title') || '', 
   viewURL : $link.data('href') || '', 
   entity : $link.data('entity') || '',
   row : $link.data('row') 
}; 

Upvotes: 1

Related Questions