spread operator converting objects to array

16,924

Solution 1

"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);

Solution 2

You can use Object.entries to get [key, value] pairs, and map them to an array of objects using computed property names:

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

const result = Object.entries(data).map(([key, value]) => ({ [key]: value }));

console.log(result);

Solution 3

I'm afraid you cant use to spread operator like in your example, however you can produce the desired output with reduce.

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

let resArr = Object.keys(data).reduce((arr, e) => {
  arr.push({[e]: data[e]});
  return arr;
}, []);

console.log(resArr);
Share:
16,924
Turnipdabeets
Author by

Turnipdabeets

BY DAY: I love to code, especially in React (Native). BY NIGHT: I play trumpet. :P

Updated on June 19, 2022

Comments

  • Turnipdabeets
    Turnipdabeets almost 2 years

    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?