dpatnaik
dpatnaik

Reputation: 188

How to retrieve data-attribute value of which is an array of objects with jquery

My data-attribute looks something like this:

data-image="[object Object],[object Object] "

Upvotes: 3

Views: 2015

Answers (3)

guest271314
guest271314

Reputation: 1

If the data-* attribute is set at HTML use valid JSON for the value, JSON.stringify() and JSON.parse() to set and get the data-* attribute value as a JavaScript object. You can get and set the HTML data-* attribute using HTMLElement.dataset

console.log(
  JSON.parse(
    document.querySelector("div").dataset.image
  )
)
<!-- set `data-*` attribute value as valid `JSON` -->
<div data-image='[{"a":123}, {"b":456}]'></div>

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68655

Actually when you retrieve this, you will get only string with value [object Object],[object Object]. You keep your data in the data-attribute with wrong syntax. Try first make your value of data-image into JSON format and then keep in the data-image attribute. After that you can retrieve your data via (see comments)

const dataArray = [ { name: 'Name1' }, { name: 'Name2' } ];
const div = $('#div');

div.data('image', JSON.stringify(dataArray)); // keep the attribute as string 

const retrievedDataImageAsJSON = div.data('image'); // retrieve the data attribute as string
const dataObj = JSON.parse(retrievedDataImageAsJSON); // parse from JSON into JS objects.

console.log(dataObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div' data-image>

</div>

Upvotes: 1

geeky_monster
geeky_monster

Reputation: 8792

Only string/number can be stored in attributes. So just store the src of the image if you want to store image details. If for some reason you want to store an object, convert it to string first and then later when you retrieve it, convert to object.

//Convert to String 
var mystring = JSON.stringify(myobject); // store this in the attribute. 

//Convert to Object while retrieving 
var myobj = JSON.parse(mystring);

Upvotes: 2

Related Questions