4
data = [ RowDataPacket { test: '12312311' },
    RowDataPacket { test: '12312312' },
    RowDataPacket { test: '12312313' } ]

I would like to get the numbers from this object into an array in Javascript. I already tried it with .split(/(\d+)/); but I get this error in Chrome:

Uncaught TypeError: data.split is not a function.

How can I extract the numbers?

Teemu
  • 22,918
  • 7
  • 53
  • 106
Suppenterrine
  • 55
  • 1
  • 7

3 Answers3

6

Your attempt will not work because .split() is a string method - it's used for breaking up a string into an array. You already have an array. JSON seems to be irrelevant here, as what you've shared is not JSON.

You can use Array.map() to mutate each member of an array. You want to get each member's test value, and parse it.

var data = [ { test: '12312311' }, { test: '12312312' }, { test: '12312313' } ];
var result = data.map(obj => parseInt(obj.test));
console.log(result);
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
4

You can use the map method in combination with destructuring to return a new array. + can be used as a coercion operator to change string values into numbers.

data.map(({test}) => +test);

let data = [ { test: '12312311' }, { test: '12312312' }, { test: '12312313' } ],
    
r = data.map(({test}) => +test);

console.log(r);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
0

It is as easy as a simple forEach. But first you should ignore RowDataPacket somehow, then below code should work.

var numbers = [];
data.forEach(function( item ) {
  numbers.push(parseInt(item.test));
});
sadrzadehsina
  • 1,331
  • 13
  • 26