Traversing JSON data in a recursive manner without definite knowledge of its size or nesting levels

Currently, I'm working on a chrome app that utilizes local storage. The backend returns JSON data which I then save locally and encrypt all the items within the JSON. I have multiple sets of JSON with different encryption functions for each set.

I attempted to create a dynamic function that can return a copy of these JSON sets with each item encrypted, but I couldn't get it to work properly. My JSON includes both arrays and objects.

My question is, is it possible to create such a dynamic function? If yes, could someone provide me with a working sample?

Just so you know, I'm using angularJS and here is the code snippet I am currently working with:

// This function returns a copy of JSON with encrypted values.
fac.encryptData = function(param) {
    // Encryption logic goes here
};

In essence, I have separate functions for encrypting different JSON structures, and I want to consolidate them into a single dynamic function to handle encryption for various types of JSON data.

Answer №1

Here is a suggestion:

function encryptData(data) {
    var encryptedData = null;
    if (typeof data == 'object') {
        encryptedData = {};
        angular.forEach(data, function (value, key) {
            encryptedData[key] = encryptData(value);
        }
    } else if (data instanceof Array) {
        encryptedData = [];
        for (var i = 0; i < data.length; i++) {
            encryptedData.push(encryptData(data[i]));
        }
    } else {
        encryptedData = base64.encode(data.toString());
    }
    return encryptedData;
}

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

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Exploring JSON and jQuery to Address Filtering Challenges

Excuse the interruption, but I need some assistance with my filters. Below is the code I'm currently working on; however, none of my attempts have been implemented yet (the dropdown menu and checkboxes remain non-functional) to make it easier for you ...

Can React JSX and non-JSX components be combined in a single project?

I'm currently faced with a question: If I have a parent component in JSX but need to include an HTML tag like <i class="fa fa-window-maximize" aria-hidden="true"></i>, which is not supported by React JSX (correct me if I'm wrong), can ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Issue with jQuery select box (roblaplaca) and its custom scroll bar functionality not functioning as expected

Recently, I implemented the custom select box script from . This script allows for two select boxes, where the second one updates dynamically using AJAX when there is a change in the first select box. Below is a sample of the HTML code: <option>One& ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Unexpected behavior of ion-select: No rendering of selected value when applied to filtered data

I came across an unexpected issue with the dynamic data filtering feature of ion-select. In my application, users are required to choose three unique security questions during registration. I have an array of available questions: questions: Array<{isSe ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...

Create a dropdown menu with selectable options using a b-form-select

I am working with a b-form-select element that displays options based on user input. I am trying to figure out how to trigger a function when the user selects one of the dynamically generated <b-form-option> elements, but I am struggling to capture b ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

What sets defineProps<{({})}>() apart from defineProps({ }) syntax?

While examining some code written by another developer, I came across the syntax defineProps<({})>(). After doing some research, I couldn't find any resources that helped me understand this particular syntax. My Way of Defining Props defineProp ...

Developing New Arrays from JSON Responses using AngularJS

I have a function linked to the factory for controlling: fac.GetDailyCountersList = function () { return $http.get('/Data/GetDailyCountersList') } Within the controller, this is how the function is invoked: $scope.DailyCounters = null; Dai ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

"Seeking clarification on submitting forms using JQuery - a straightforward query

My goal is to trigger a form submission when the page reloads. Here's what I have so far: $('form').submit(function() { $(window).unbind("beforeunload"); }); $(window).bind("beforeunload", function() { $('#disconnectform&apo ...

Sharing data within angularJS applications can provide numerous benefits and increase

As a beginner in angularJS, I find myself still grappling with the concept of data sharing among various components like controllers, directives, and factories. It seems there are multiple methods available for facilitating communication between them -- ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...