【发布时间】:2016-08-02 16:31:21
【问题描述】:
我有两个对象数组
var arr1 =
[
{
"lastInteracted": "2016-03-31T11:13:09.000Z",
"email": "concierge@inbound.com",
"interactionCount": 2
},
{
"lastInteracted": "2016-03-31T21:06:19.000Z",
"email": "jbi@salesforce.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-29T11:15:41.000Z",
"email": "abc@insightsquared.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "diana@hubspot.com",
"interactionCount": 1
}
]
和
var arr2 =
[
{
"lastInteracted": "2016-03-31T11:13:09.000Z",
"email": "concierge@inbound.com",
"interactionCount": 2
},
{
"lastInteracted": "2016-03-31T21:06:19.000Z",
"email": "jbi@salesforce.com",
"interactionCount": 4
},
{
"lastInteracted": "2016-03-29T11:15:41.000Z",
"email": "kstachowski@insightsquared.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "hammer@hubspot.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "life@hubspot.com",
"interactionCount": 10
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "mike@hubspot.com",
"interactionCount": 18
}
]
我想合并这两个数组,这样如果两个数组中都存在一个对象的电子邮件,则将 arr1 中的 interactionCount 与 arr2 进行比较,否则返回 arr1 或 arr2 的交互计数。
结果将是
var result = [
{
"lastInteracted": "2016-03-31T11:13:09.000Z",
"email": "concierge@inbound.com",
"interactionCount": 0
},
{
"lastInteracted": "2016-03-31T21:06:19.000Z",
"email": "jbi@salesforce.com",
"interactionCount": -4
},
{
"lastInteracted": "2016-03-29T11:15:41.000Z",
"email": "abc@insightsquared.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "diana@hubspot.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-29T11:15:41.000Z",
"email": "kstachowski@insightsquared.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "hammer@hubspot.com",
"interactionCount": 1
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "life@hubspot.com",
"interactionCount": 10
},
{
"lastInteracted": "2016-03-24T10:02:29.000Z",
"email": "mike@hubspot.com",
"interactionCount": 18
}
]
【问题讨论】:
-
我已经完成了这些解决方案,但它们并没有满足我的需求。如果您可以查看结果数组,也许它会更清晰,因为我不仅想消除重复项,而且还希望在存在重复项的地方获得值的差异。
标签: javascript arrays underscore.js lodash