尝试使用lodash组合两个API的返回值,我设法使用merge将它们的公共字段结合在一起:
var primaryCount = [
{id: 0, name: "foo", address: "one"},
{id: 1, name: "bar", address: "two"},
];
var secondaryCount = [
{franchise_id: 1, count:4},
{franchise_id: 3, count:16},
]
var merged = _.merge(_.keyBy(primaryCount, 'id'), _.keyBy(secondaryCount, 'franchise_id'));
var values = _.values(merged);
但是,我只需要同时定义了字段id
和franchise_id
的项目。但是,它产生的字段仅存在于其中一个字段中(我只需要id:1
):
[
{
"id": 0,
"name": "foo",
"address": "one"
},
{
"id": 1,
"name": "bar",
"address": "two",
"franchise_id": 1,
"count": 4
},
{
"franchise_id": 3,
"count": 16
}
]
我尝试使用像这样的过滤器,但是这两个都返回了一个空数组:
var leftFiltered = _.filter(values, ['id', null]);
var rightFiltered = _.filter(leftFiltered, ['franchise_id', undefined]);
我该如何进行内部合并?
[
{
"id": 1,
"name": "bar",
"address": "two",
"franchise_id": 1,
"count": 4
},
]
答案 0 :(得分:0)
您可以创建自定义过滤和映射逻辑,也可以使用类似lodash-joins
#### Example:
> var _ = require('index.js');
> var left = [
... {id: 'c', left: 0},
... {id: 'c', left: 1},
... {id: 'e', left: 2},
... ],
... right = [
... {id: 'a', right: 0},
... {id: 'b', right: 1},
... {id: 'c', right: 2},
... {id: 'c', right: 3},
... {id: 'd', right: 4},
... {id: 'f', right: 5},
... {id: 'g', right: 6}
... ],
... accessor = function (obj) {
... return obj['id'];
... };
>
> var a = _.hashInnerJoin(left, accessor, right, accessor);
undefined
> a
[ { id: 'c', left: 0, right: 2 },
{ id: 'c', left: 1, right: 2 },
{ id: 'c', left: 0, right: 3 },
{ id: 'c', left: 1, right: 3 } ]
>
> var b = _.nestedLoopLeftOuterJoin(left, accessor, right, accessor);
undefined
> b
[ { id: 'c', left: 0, right: 2 },
{ id: 'c', left: 0, right: 3 },
{ id: 'c', left: 1, right: 2 },
{ id: 'c', left: 1, right: 3 },
{ id: 'e', left: 2 } ]
>
> var c = _.sortedMergeFullOuterJoin(left, accessor, right, accessor);
undefined
> c
[ { id: 'a', right: 0 },
{ id: 'b', right: 1 },
{ id: 'c', left: 0, right: 2 },
{ id: 'c', left: 0, right: 3 },
{ id: 'c', left: 1, right: 2 },
{ id: 'c', left: 1, right: 3 },
{ id: 'd', right: 4 },
{ id: 'e', left: 2 },
{ id: 'f', right: 5 },
{ id: 'g', right: 6 } ]