I have 2 json object.
the first one holds data from the client form.
{
       "name": "Example name",
       "company": {
         "name": "new company",
         "size": "FIVE",
         "licenseInfo": {
            "isActive": "0"
         }
       }
}
and in my other object, I know which fields are modified in this form. If value is true then it has changed. The plugin I use gives me this information.
{
       "name": true,
       "company": { 
         "size": true,
         "licenseInfo": {
            "isActive": true
         }
       }
}
I want to compare these 2 objects and get a submit object with only changed data as follows. company name has not been changed and I do not want to submit company.name
{
       "name": "Example name",
       "company": { 
         "size": "FIVE",
         "licenseInfo": {
            "isActive": "0"
         }
       }
}
I can manually control the fields one by one, but I want to create a dynamic compare function so I can use it on my other forms.
Advertisement
Answer
Iterate by keys (compare) and add input values…
const input = { "name": "Example name", "company": { "name": "new company", "size": "FIVE", "licenseInfo": { "isActive": "0" } } }
const compare = { "name": true, "company": { "size": true, "licenseInfo": { "isActive": true } } }
function filter(input, compare) {
    const output = {};
    for (const key in compare)
        output[key] = typeof compare[key] == "object"
            ? filter(input[key], compare[key])
            : input[key];
    return output;
}
console.log(filter(input, compare));