Koby Douek
Koby Douek

Reputation: 16673

Casting an object to an Array using Array.from

I'm trying to create an ArrayBuffer from a WebSocket's stringified data.

The stringified data is a Float32Array.

Here's what I attempted:

var parsed = JSON.parse(streamData);
var arrayed = Array.from(parsed);
var arr32 = Float32Array.from(arrayed);
var kbuff = new ArrayBuffer(arr32);

The variable parsed looks like this:

enter image description here

But then my Array.from results in an empty array:

enter image description here

What am I missing here? And - Is this the proper way of creating my ArrayBuffer?

Upvotes: 0

Views: 58

Answers (2)

V.Tur
V.Tur

Reputation: 1427

For Array.from need to iterable argument with property length. Try to use Object.values(parsed) for getting array from your parsed values and then use Float32Array, seems it's can help you. Or you can get array from pais [key, value] use Objest.entries(parsed)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192006

Array.from() requires the object to have a length property. Use Object.values() instead:

const parsed = {
  0: 'a',
  1: 'b',
  2: 'c',
}

const arrayed1 = Array.from(parsed);
const arrayed2 = Object.values(parsed);

console.log({ arrayed1 });
console.log({ arrayed2 });

Upvotes: 4

Related Questions