Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send array of objects with keys to API?

Tags:

javascript

I have a few spans:

<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />

And operations on them:

const spans = document.querySelectorAll('span');

const list = [];

spans.forEach(function(span) {
    if (typeof list[span.getAttribute('class')] === 'undefined') {
    list[span.getAttribute('class')] = [];
  }

  list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});

console.log(list);
console.log(JSON.stringify(list));

But JSON.stringify return empty array.

How can I count the number of occurrences of data-id at a given SPAN the easiest way and next get it to string? I would like to send this data to API.

Fiddle: https://jsfiddle.net/x7thc59v/

like image 726
xatac Avatar asked Aug 24 '19 09:08

xatac


Video Answer


1 Answers

here is a code that's working: use object instead of array to have key. use var instead of const to modify your variable;

const spans = document.querySelectorAll('span');

var list = {};

spans.forEach(function(span) {
    if (typeof list[span.getAttribute('class')] === 'undefined') {
    list[span.getAttribute('class')] = [];
  }

  list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});

console.log(list);
console.log(JSON.stringify(list));
like image 75
NoxFly Avatar answered Sep 20 '22 01:09

NoxFly