我该如何合并以下划线JS对象数组 [英] How can i merge array of objects with underscore js
问题描述
我有对象,像这样的数组:
I have an array of objects like this:
array1 = [
{field: 'username', display: 'username', hide: true},
{field: 'age', display: 'Age', hide: true},
{field: 'height', display: 'Height', hide: true}
]
然后,我有数组2:
Then I have array2:
array2 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', hide: false}
]
我想通过自己的领域,以这两个数组合并,即最终的结果应该是:
I want to merge these two arrays by their field i.e. the final result should be:
array3 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', display: 'Age', hide: false},
{field: 'height', display: 'Height', hide: true}
]
我试过 VAR newObj = _.extend(数组1,数组2);
但它并没有给我我想要的东西。
I tried var newObj = _.extend(array1, array2);
but it didn't give me what I want.
推荐答案
有没有一个功能,将做到这一点,因为它的一个相当专业化经营。然而,下划线功能的一个相当简单的组成:
There's no one function that will do it, as its a fairly specialized operation. However, its a fairly simple composition of underscore functions:
_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field')))
我们使用 indexBy
开启数组到键控上的字段
的值,然后<$ C $对象C>延长做我们想要的。最后,值
把它放回一个数组。
We use indexBy
to turn the arrays into objects keyed on the field
value, and then extend
does what we want. Finally, values
turns it back into an array.
请注意,虽然这不作任何保证有关订单,在目前的 _
和V8实现最终的阵列将是东西从数组1
之后的事情从数组2
不在数组1
,在整理原来的订货每个数组的。
Note that while this doesn't make any guarantees about the order, in the current _
and v8 implementations the final array will be the things from array1
followed by the things from array2
that aren't in array1
, sorted in the original ordering of each array.
另外请注意, _。延长
函数的第一个参数的破坏性,而这不会改变任何数组。
Also note that the _.extend
function is destructive on the first argument, while this doesn't change either array.
如果你想确保顺序是一样的原始的数组1
:
If you want to be sure that the order is the same as the original array1
:
order = _.object(_.map(array1, function(obj, i) { return [obj.field, i]; }))
_.sortBy(_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field'))), function(obj) { order[obj.field]; })
下面我们做位置的查找表,然后基于查找表的原始解决方案进行排序。
Here we make a lookup table of positions and then sort the original solution based on the lookup table.
这篇关于我该如何合并以下划线JS对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!