Enable access to nested properties by utilizing this specific object structure

Looking for a "whitelist" object with the following structure:

{
    a: {
        b: {
            c: ''
        }
    }
}

Trying to apply this object to the following:

{
    a: {
        b: {
            c: 1
        },
        d: 2,
        e: 3
    }
}

The expected result should be:

{
    a: {
        b: {
            c: 1
        }
    }
}

Any suggestions on how to implement this using underscore? I tried using _.pick but had issues with the nested properties.

Answer №1

Utilizing recursion in conjunction with Array.prototype.reduce():

function retrievePaths(obj, whiteList) {  
  return Object.keys(whiteList)
    .reduce(function(whiteObj, key) {
      if (!obj.hasOwnProperty(key)) {
      } else if(typeof obj[key] === 'object') {
        whiteObj[key] = retrievePaths(obj[key], whiteList[key]);
      } else {
        whiteObj[key] = obj[key];
      }
    
      return whiteObj;
    }, {})
}

var whiteList = {
  a: {
    b: {
      c: ''
    }
  },
  g: ''
};

var obj = {
  a: {
    b: {
      c: 1
    },
    d: 2,
    e: 3
  }
};

var result = retrievePaths(obj, whiteList);

console.log(result);

Answer №2

In my approach, I create a function that filters nested properties in an object:

function filterObjectProperties(whitelist, obj) {
    if (_.contains(['boolean', 'number', 'string'], typeof obj))
        return obj;
    var filteredObj = {};
    _.each(whitelist, function(value, propName) {
        var originalValue = obj[propName];
        if (originalValue !== undefined)
            filteredObj[propName] = filterObjectProperties(
                value, originalValue);
    });
    return filteredObj;
}

To use this function, pass your whitelist object as whitelist and the target object as obj.

Answer №3

To avoid creating a custom function, an alternative approach is to utilize the built-in object methods provided by JavaScript like JSON.stringify and JSON.parse. JSON.stringify takes up to three arguments (value, replacer?, space?). The replacer parameter can either be a customized node visitor function or an array that specifies the property keys to include. With this in mind, the following code snippet demonstrates how you can achieve your desired outcome:

var obj= {
    a: {
        b: {
            c: 1
        },
        d: 2,
        e: 3
    }
};
var tempstr=JSON.stringify(obj.a,['b']);
var newobj=JSON.parse(tempstr);
obj.a=newobj;

After running the above code, accessing 'obj' should now return the whitelisted object as specified.

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

struggling with parsing Json data in Groovy

My JSON response contains data like {"canMerge":false,"conflicted":true,"outcome":"CONFLICTED","vetoes":[{"summaryMessage":"Requires approvals","detailedMessage":"You need 2 more approvals before this pull request can be merged."}]} I am trying to filter ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

Tips for preventing a function from being triggered twice during a state change

I'm currently working with a react component that looks like this: const [filter, setFilter] = useState(valueFromProps); const [value, setValue] = useState(valueFromProps); const initialRender = useRef(true); useEffect(() => { if (initialRender. ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...

The compiler mistakenly infers an incorrect type while utilizing a default value for a discriminated union type

I am currently working on a simplified component: export type BaseProps = { size?: 'xs' | 'sm' | 'md' | 'lg'; } type ButtonAsButtonProps = Omit<React.ComponentPropsWithoutRef<'button'>, ' ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

Mastering the ng-if directive in Angular can help you easily display or hide content based on boolean

Having trouble figuring out what to insert in the last span element where it mentions "I_DO_NOT_KNOW", here is the markup provided: <div class="row"> <div class="key" translate>Label</div> <div class="value form-group"> < ...

How can we ensure that multiple forms are validated when submitting one form in AngularJS?

Is there a way to validate two forms on the same page (address1 and address2) using AngularJS when the button on one of the forms is clicked? ` ...

Animate numbers in response to scroll with JQuery

I am currently working on a project where I need to create a counter that triggers at a specific scroll value. Essentially, I want users to see animated numbers incrementing from 0 to a pre-defined number once they reach a certain point while scrolling. H ...

Problem encountered during the transfer of JSON data from PHP to JavaScript

Currently, I am working on a PHP file that extracts data from a database to display it on a chart using the Chart.js library. The chart is functioning properly, but I am facing an issue where I need to use the json_encode() function to pass the array value ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...

Jackson transforms DateTime to and from WCF DateTime during serialization and deserialization

When it comes to serializing and deserializing objects, I rely on Jackson. However, there seems to be an issue with the .NET WCF DateTime JSON format that includes a Time Zone. Jackson is unable to successfully deserialize this type of JSON into an object. ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

A helpful guide on how to separate text using Java Script and the "/" character

Just diving into the world of JavaScript and encountering some challenges with splitting text. The string that needs to be split looks like this: mobile)/index.m3u8 The desired output should be: mobile and index.m3u8 I attempted to use .split("&bso ...

Associating information with a dropdown menu

My goal is to bind a drop-down using a global variable (the array name). The binding works correctly here: Click here - dropdown is populating fine var name = ['us', 'china', 'kenya', 'us', 'china', &ap ...

Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

AngularJS: handling multiple asynchronous requests

When I make multiple ajax calls in my code, I noticed that the API is only reached after all the ajax calls have been executed. Below you can see the JavaScript code: function test = function(){ var entity = {}; entity.Number = 1; ...