简体   繁体   中英

Use Lodash to compare, match and filter two objects

I have one object that looks like this (with a nested object):

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" 
}

and another that looks like this (also with a nested object):

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

The second object represents the "Filter Criteria" on that first object. How can I use lodash to return an object that looks like this:

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

Essentially, I need the result to be only the key value pairs that match the keys in the filter object. I also need to filter on the nested objects

I don't need to use lodash but I know a lot of their features would make this easy. Thank you in advance.

You could use the keys of filter, Array#reduce for iterating the keys and Object.assign for assembling the object.

 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); 

For deep nested object, you could use an recursive approach with a closure over the source object.

 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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM