传播运算符将对象转换为数组

spread operator converting objects to array

我正在尝试转换这样的数据结构:

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

变成这样的结构:

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

像这样使用扩展运算符:[...data] returns 任何空数组。

我也试过了[{...data}]

有没有办法使用展开运算符来得到想要的结果?另外,为什么这种方法不起作用?

恐怕您不能像示例中那样使用传播运算符,但是您可以使用 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);

"Is there a way to use the spread operator to get the desired result?" 简答,没有。 (请参阅下文了解您要完成的任务的替代解决方案)

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

它不起作用,因为根据 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."

正如文档所说,根据 "Rest/Spread Properties proposal",您不能将对象属性扩展到一个数组中,对象总是将它们的属性扩展到一个新对象中。同样,数组不会扩散到一个对象上,它们只会扩散到一个新数组上。

备选方案:

您可以使用 Object.keys().map() 轻松完成此操作。 Object.keys() will get an array of the keys of the object, and Array.map() 会将它们映射到所需结构的数组中,如下所示:

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

您可以使用 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);