Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
Turnipdabeets Avatar asked Jul 24 '17 16:07

Turnipdabeets


People also ask

Can you spread an object into an array?

Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.

Can we use spread operator on array?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.

How do you spread an array of objects?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax: Function arguments list ( myFunction(a, ... iterableObj, b) )


1 Answers

"Is there a way to use the spread operator to get the desired result?" Short answer, no. (see below for alternate solution to what you're trying to accomplish)

"Also, why doesn't this approach work?"

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."

Like the docs say, according to the "Rest/Spread Properties proposal", you can't spread object properties onto an array, objects will always spread their properties onto a new object. Likewise, arrays will not spread onto an object, they will only spread onto a new array.

Alternative solution:

You can do this fairly easily with Object.keys().map(). Object.keys() will get an array of the keys of the object, and Array.map() will map them into an array of the desired structure, like so:

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);
like image 116
mhodges Avatar answered Oct 07 '22 23:10

mhodges