[英]How can I use spread syntax to copy object properties from multiple unknown objects in JavaScript?
I would like to use spread syntax to copy properties from several unknown objects into one object.我想使用扩展语法将几个未知对象的属性复制到一个 object 中。 Something like this:
像这样的东西:
var array = [{a:0}, {b:1}, {c:2}]; // This array could hold any number of objects
// This function should take the objects in the array and use spread syntax to create a new object.
function merge(arr) { /* Code I wish I knew */ } // returns an object
var combo = merge(array);
console.log(combo); // {a:0, b:1, c:2}
I am aware of Object.assign
.我知道
Object.assign
。 My reason for asking this question is just to see if this sort of thing can be done with spread syntax.我问这个问题的原因只是想看看这种事情是否可以用扩展语法来完成。 Additionally, I'm concerned with V8's Hidden Classes.
此外,我关心 V8 的隐藏类。 From what I understand, modifying an object after it is instantiated negatively impacts the performance of the Hidden Class.
据我了解,在实例化 object 后对其进行修改会对隐藏 Class 的性能产生负面影响。 I've read that Spread doesn't have this issue, possibly because it instantiates the object with all of the properties of the other objects.
我读过Spread没有这个问题,可能是因为它用其他对象的所有属性实例化了object。
You can use a combination of Array.reduce
with Object.assign
:您可以将
Array.reduce
与Object.assign
结合使用:
var array = [{a:0}, {b:1}, {c:2}]; function merge(arr) { return array.reduce((x,y) => Object.assign(x, y)) // // per the comments, if we don't want to mutate the original object we can do instead: // return array.reduce((x,y) => Object.assign(x, y), {}) } var combo = merge(array); console.log(combo);
You can use Array#reduce
to iterate the array and merge the children into one object:您可以使用
Array#reduce
迭代数组并将子元素合并为一个 object:
var array = [{a:0}, {b:1}, {c:2}]; function merge(arr) { return arr.reduce((acc, cur) => ({...acc, ...cur })); } var combo = merge(array); console.log(combo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.