Turnipdabeets Turnipdabeets - 3 years ago 105
Javascript Question

spread operator converting objects to array

I'm trying to convert a data structure like this:

data = {
0:{A:a},
1:{B:b},
2:{C:c},
}


into a structure like this:

[
{0:{A:a}},
{1:{B:b}},
{2:{C:c}},
]


Using the spread operator like this:
[...data]
returns any empty array.

I also tried
[{...data}]


Is there a way to use the spread operator to get the desired result? Also, why doesn't this approach work?

Answer Source

It doesn't work because according to the MDN docs

"The Rest/Spread Properties for ECMAScript proposal (stage 3) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object."

You can do what you're trying to do very easily with Object.keys().map() though.

var data = { 
  0:{A:"a"}, 
  1:{B:"b"}, 
  2:{C:"c"}, 
}

var result = Object.keys(data).map(function (key) {
   return { [key]: data[key] };
});
console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download