本文介绍了JavaScript扩展数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组.在循环过程中,我将不同的属性附加到每个条目.

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?

让我们考虑一下:

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}]

推荐答案

如果没有库,那么优雅的单行代码会有些困难.但是,如果您具有某种extend函数,则可能是:

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

extend函数将需要组合多个对象(作为单独的参数传递). jQuery中可以使用jQuery.extend这样的功能,underscore.js也具有一个功能.

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.

这篇关于JavaScript扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 06:21