我如何将对象数组与下划线 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}
]
然后我有 array2:
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(array1, array2);
但它没有给我我想要的.
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
将数组转换为以 field
值为键的对象,然后 extend
做我们想要的.最后,values
将其转回数组.
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 实现中,最终的数组将是来自 array1
的东西,然后是array2
中不在 array1
中的东西,按照每个数组的原始顺序排序.
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.
另请注意,_.extend
函数对第一个参数是破坏性的,而这不会改变任何一个数组.
Also note that the _.extend
function is destructive on the first argument, while this doesn't change either array.
如果要确定顺序和原来的array1
一样:
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屋!