问题
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