1

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'), ... })
Tony Beninate
  • 1,926
  • 1
  • 24
  • 44
  • The spread operator? `...elem.data` – Silidrone Mar 13 '21 at 11:44
  • 1
    From [the documentation](https://api.jquery.com/data/#data), it seems like what you've got should work...? (Provided you havent' added more `data-` attributes after the first time you used jQuery's `data` function on the element, since `data` is not just an accessor for `data-` attributes.) – T.J. Crowder Mar 13 '21 at 11:49
  • 1
    @Silidrone - Just FWIW, [it's not an operator](https://stackoverflow.com/questions/44934828/is-it-spread-syntax-or-the-spread-operator). Operators can't do what spread and rest do. – T.J. Crowder Mar 13 '21 at 11:50
  • @T.J.Crowder that's what was really getting me, i thought for sure what i had should be working. So i just tried it again, and now it is. I could have swore this is exactly what i was doing last night, but idk.. it was very late XD – Tony Beninate Mar 13 '21 at 13:13
  • @T.J.Crowder So it's actual name is spread syntax? – Silidrone Mar 13 '21 at 18:32
  • 1
    @Silidrone - Or just "spread," but yeah, spread syntax, spread notation.... – T.J. Crowder Mar 14 '21 at 08:05

2 Answers2

2

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>
T J
  • 42,762
  • 13
  • 83
  • 138
-1

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)
Silidrone
  • 1,471
  • 4
  • 20
  • 35
  • I hope you understand that just consul login data itself alone will give you 100% same result in your snippet? – ikiK Mar 13 '21 at 14:12
  • Yes I do. I put it for example purposes to show how it can be used. I constructed a new object with the properties of the data object by spreading it, and then printed it. In fact, let me edit it to make the example clearer for future visitors. – Silidrone Mar 13 '21 at 18:24