javascript - How to send array of objects with keys to API? - Stack Overflow

I have a few spans:<span class="first" data-id="1" ><span class="se

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: /

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/x7thc59v/

Share Improve this question asked Aug 24, 2019 at 9:06 xatacxatac 534 bronze badges 1
  • try const list = {} JSON.stringify will return empty array for any not number indexes. And you can use const obj = {} instead of list since you don't want list you want object. – jcubic Commented Aug 24, 2019 at 9:09
Add a ment  | 

4 Answers 4

Reset to default 2

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));

If you want output like this [{"first":["1"]},{"second":["4","2"]},{"third":["5"]}]

Then you can follow this appraoch

const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
 const className = span.getAttribute('class');
 const valIndex = list.findIndex(val => val[className]);
 const hasVal = valIndex !== -1;
 if (className && hasVal) {
  const preVal = list[valIndex][className];
  list[valIndex][className] = preVal.concat(span.getAttribute('data-id'));
 } else if (className && !hasVal){
  list.push({[className]: [span.getAttribute('data-id')]});
 }
});
console.log(list);
console.log(JSON.stringify(list));

Here is working jsfiddle;

The JSON.stringify function will not serialise string keys added to an array, only the numeric ones.

The trivial fix then is to replace const list = [] with const list = {} and then update the code that uses the results to expect an Object instead of an Array.

More generally, you should reduce the repetition in your code, especially the repeated calls to span.getAttribute('class'):

const spans = document.querySelectorAll('span');
const list = {};

spans.forEach(function(span) {
    const cls = span.className;
    const id = span.getAttribute('data-id');

    list[cls] = list[cls] || [];   // ensure the array exists
    list[cls].push(id);
});

I think you wanted the list to be an object as the way you were trying to access the property of list by the class name.

Also rather than mutating an external object using forEach its better to use Array.prototype.reduce on the NodeList returned from document.querySelectorAll() call:

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

//With Array.prototype.reduce
const list = Array.prototype.reduce.call(spans, function(acc, span) {
    const attr = span.getAttribute('class');
    const dataId = span.getAttribute('data-id');
    acc[attr] ? acc[attr].push(dataId) : (acc[attr] = [dataId]);
    return acc;
}, {});

console.log(list);
console.log(JSON.stringify(list));
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340029a4623283.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信