JavaScript extend array

帅比萌擦擦* 提交于 2019-12-25 05:15:14

问题


I have an array of objects. During the loop I append different properties to each entry.

My question - how do I make sure every entry has all the properties of each entry?

Let's consider this:

var myArray = [{A: 1}, {B: 2}, {C: 3}];

Now I want to run some elegant one-liner to convert this array into:

[{A: 1, B:2, C: 3}, {A: 1, B:2, C: 3}, {A: 1, B:2, C: 3}]

回答1:


An elegant one-liner is a bit difficult without a library. But if you have some kind of extend function, then it could be:

myArray.map(function(v) { return extend.apply(null, [{}].concat(myArray)); });

The extend function would require several objects (passed as separate arguments) to be combined. Such a function is available in jQuery as jQuery.extend, and underscore.js also has one.



来源:https://stackoverflow.com/questions/10688569/javascript-extend-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!