Tony Beninate
Tony Beninate

Reputation: 1985

How to pass all of an element's data attributes

I want to be able to pass all of an element's data attributes, without have to individually specify them. For example:

function foo(elem) {
  $.ajax({
    type: 'POST',
    data: JSON.stringify(elem.data()),
    ...

However, when I simply supply elem.data(), nothing is actually getting passed. Is there a way to accomplish this without having to individually specify, like:

data: JSON.stringify({ foo: elem.data('foo'), ... })

Upvotes: 1

Views: 249

Answers (2)

Silidrone
Silidrone

Reputation: 1581

Try using the spread operator syntax:

const foo = {
  a: 'a',
  b: 'b',
  c: 'c'
}

const boo = {
  d: 'd',
  e: 'e',
  f: 'f'
}

const foo_boo = {
  ...foo,
  ...boo
}

console.log(foo_boo)

Upvotes: -1

T J
T J

Reputation: 43156

Since you're using jQuery data() method I'm assuming elem here is a jQuery object.

You can use native elements dataset property for this, like

{...elem.get(0).dataset} along with JS spread operator

const el = document.querySelector('div');
console.log({ ...el.dataset});
<div data-test-id="test" data-test-key="test-key"></div>

Upvotes: 2

Related Questions