使用Lodash比较,匹配和过滤两个对象

时间:2017-03-23 16:35:57

标签: javascript json object lodash

我有一个看起来像这样的对象(带有嵌套对象):

var data = {
"results":{  
           "Description":"There was a record added",
           "resultTimestamp":"2017-03-23T21:56:05Z"
        },
"service":"FDSY",
"StartTimestamp":"2017-03-23T21:55:17Z",
"eventId":"033dc019-0b8a-4af22",
"assetId":"TenGigE0/14/0/0.55",
"assetType":"CLCI" 
}

和另一个看起来像这样(也使用嵌套对象):

var filter = {
"results":{  
           "Description":"",
        },
"service":"",
"eventId":"",
"assetType":"" 
}

第二个对象表示第一个对象上的“过滤条件”。如何使用lodash返回如下所示的对象:

var result = {
 "results":{  
     "Description":"There was a record added"
 },
"service":"FDSY",
"eventId":"033dc019-0b8a-4af22",
"assetType":"CLCI" 
}

基本上,我需要结果只是与过滤器对象中的键匹配的键值对。我还需要对嵌套对象进行过滤

我不需要使用lodash,但我知道他们的很多功能会让这很容易。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用过滤器的键Array#reduce来迭代键,使用Object.assign来组装对象。

var data = { service: "FDSY", StartTimestamp: "2017-03-23T21:55:17Z", eventId: "033dc019-0b8a-4af22", assetId: "TenGigE0/14/0/0.55", assetType: "CLCI" },
    filter = { service: "", eventId: "", assetType: "" },
    result = Object.keys(filter).reduce((r, k) => Object.assign(r, { [k]: data[k] }), {});

console.log(result);

ES5

var data = { service: "FDSY", StartTimestamp: "2017-03-23T21:55:17Z", eventId: "033dc019-0b8a-4af22", assetId: "TenGigE0/14/0/0.55", assetType: "CLCI" },
    filter = { service: "", eventId: "", assetType: "" },
    result = Object.keys(filter).reduce(function (r, k) {
        r[k] = data[k];
        return r;
    }, {});

console.log(result);

对于深层嵌套对象,可以使用带有源对象闭包的递归方法。

var data = { results: { Description: "There was a record added", resultTimestamp: "2017-03-23T21:56:05Z", foo: {bar:42} }, service: "FDSY", StartTimestamp: "2017-03-23T21:55:17Z", eventId: "033dc019-0b8a-4af22", assetId: "TenGigE0/14/0/0.55", assetType: "CLCI" },
    filter = { results: { Description: "", foo: { bar: "" } }, service: "", eventId: "", assetType: "" },
    result = Object.keys(filter).reduce(function iter(source) {
        return function (r, k) {
            r[k] = filter[k] && typeof filter[k] === 'object' ?
                Object.keys(filter[k]).reduce(iter(source[k]), {}) :
                source[k];
            return r;
        };
    }(data), {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }