"Is it possible to achieve the desired outcome using the spread operator?" In short, no. (see below for an alternative approach)
"Why does this method not yield the desired result?"
This method falls short because as specified in the MDN documentation
"The Rest/Spread Properties for ECMAScript proposal (stage 3) introduces spread properties within object literals. It copies own enumerable properties from a provided object onto a new object."
As indicated in the documentation, according to the "Rest/Spread Properties proposal", spreading object properties onto an array is not feasible; objects will only spread their properties onto another object. Similarly, arrays cannot spread onto an object, but instead, they will spread onto a new array.
Alternate method:
You can accomplish this task quite easily using Object.keys().map()
. Utilizing Object.keys()
retrieves an array of the object's keys, and employing Array.map()
allows you to map them into an array with the preferred structure, like the example below:
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);