Leverage the power of Lodash for comparing, matching, and filtering between two objects

I have a comparison to make between two different objects, each containing nested objects:

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 object structured like this:

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

The second object is intended to represent the criteria for filtering the first object. How can I utilize lodash functions to create an object that matches this pattern:

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

In essence, I require the result to only include key-value pairs that align with the keys specified in the filter object, including those within nested objects.

While not mandatory, I acknowledge that utilizing lodash could simplify this process. Your assistance is greatly appreciated.

Answer №1

To iterate through the keys and assemble an object, you can utilize filter keys along with Array#reduce for iteration and Object.assign for object assembly.

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

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

If dealing with deeply nested objects, a recursive approach with closure over the source object can be used:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

What sets apart the browser's debugger from Angular's setTimeout function?

I'm currently working on an angular application that is embedded within a larger application that I do not have access to. I am using a router to navigate between pages after a pop-up modal has been acknowledged (checkbox & button). It's crucial ...

Returning the pdf generated by html2pdf to the server

I am facing an issue with sending a PDF generated on the client side using html2pdf to a server. After successfully converting the PDF to base64, I want to send it back using axios. Below is the code snippet from my client-side implementation: function my ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

Error message for empty input is not being displayed upon submission in Bootstrap validation

I've been attempting to implement Bootstrap validation in a form with the following desired outcome: Upon submission of the form, if the "First name" field is left empty, a message saying "Please enter a name" should appear below the field. If the f ...

The MainViewController is not receiving any notifications from the NSNotificationCenter

In my application, my main class is a UITableViewController. The JSON data is fetched using a ConnectionManager class and parsed with an ItemManager class. Inter-class communication is facilitated by the NotificationCenter. When there's a response fro ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

How can I retrieve the source code of a popup window and save it as

Is there a method to save the content of a popup window from an external domain as a string, when opened with: window.open('html'); Alternatively, is it possible to redirect the output of the popup into a string? For example, using Chrome' ...

python change all the keys to string format

I am facing an issue with a nested dictionary in Python that contains numeric keys. When I try to store this dictionary as JSON, I encounter errors due to the numeric keys not being able to be stored directly. The code snippet provided below attempts to ad ...

Choose the ngModel option from the dropdown menu

I have a project where I need the first question from a list to be displayed automatically. I found an example of how to do this using the index, like so: <select> <option *ngFor="let answer of answers; let i = index" [value]="answer.id" [selec ...

Having trouble with your JSONP callback not being received?

When attempting to make a JSONP request to yellowapi (Yellow Pages) and specifying a callback, I encountered an "invalid label" error. Below is the code I currently have: $.ajax({ dataType: 'jsonp', cache : false, url: "http://api.sandbox.yell ...

The JSON primitive is not valid: lookupID."&StackTrace":"

I am puzzled by the error I'm getting. Whenever I enclose the variables in quotes, the text is sent instead of the actual variable value. {"Message":"Invalid JSON primitive: lookupID.","StackTrace":" at System.Web.Script.Serialization.JavaScriptO ...

How to dynamically load a file based on the chosen option value in React

Two select textboxes on my page are named Choose City and Choose District. I also have some files related to cities and districts: // cities.js const cities = { "01": { "name": "City 1", "code": "01" }, ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

Maintain a sticky position with a set minimum distance from the bottom of the container

How can I position content in a container with some minimum distance to the bottom? Specifically, I want the blue element to stop before reaching the very bottom of the container. I could stack two containers on top of each other and only include the stic ...

"Is it possible to create a single-page website with a unique logo for each div

Is it possible to have a unique logo on each section of my single-page website? Each section has its own div. Check out my website at . Thank you in advance! ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

The C# (HTTPWEBREQUEST) is producing JSON data with incomplete information

Currently, I am faced with an issue while working on JSON and C# (using HttpWebRequest). My application is designed to download a JSON from an API REST. However, the problem arises when I download it as the JSON seems to be missing some data. It appears ...