Crisscrossed JavaScript Object: recursion and "intricate" conversion (using lodash)

Apologies for the complexity of this example; I've condensed it as much as possible to demonstrate what I'm aiming for

I have a complicated structure that needs to be traversed and transformed based on certain conditions. Here's a brief example of the structure that covers most scenarios:

{  PROP1: {
       metadata: Object,
       employee: {
           id: String,
           products: ["String", "String" , "String"],
           model: { $ref: String },
           email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8dafe3aea2a0">[email protected]</a>',
           name: { firstName: 'John', lastName: 'Smith'},
           operations: [{ action: { value: "UPDATE", model: {$ref: String }}]
       }
   },
   PROP2: {
       // similar to PROP1       
   },
   [... and so forth ...]

}

The desired outcome is to tidy up the structure before sending it to the backend;

  • If a value contains $ref, remove the key/value pair (e.g., PROP1.parent is unnecessary)
  • If a value contains value, retain only the value under the corresponding key (e.g., PROP1.employee.products should equal ['String', 'String', 'String'])
  • Omit keys like id, metadata, validity, etc., regardless of their content

The expected result should resemble this structure:

{ PROP1: {
      employee: {
          products: ['item','item','item'],
          model: {
              email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4d6c4e024f43441">[email protected]</a>',
              name: { firstName: 'John', lastName: 'Smith'},
          },
          operations: [
              { action: 'UPDATE' }
          ]
      }
  },
  PROP2: { ... }
}

I've tried various strategies using different lodash methods but couldn't quite figure this out...

Any assistance would be highly appreciated

Thank you

Answer №1

If you're looking to write pseudo code for a specific task, consider the following approach. Make sure to customize it as needed and provide additional information if you encounter any issues.

var ignoreKeyArray = ["id", ...] // list of keys to exclude
var newJSON = "{}";
for (property in JSON) {
    var newProp = parseJSON(key, property);
    insert newProp into newJSON object
}

var parseJSON = function (key, jsonBlob) {
     if (key is in ignoreKeyArray or jsonBlob contains "$ref")
         return "";

     var jsonOut = key + ": {}";
     for (child in jsonBlob) {
         add parseJSON(child) to jsonOut;
     }
     return jsonOut;
}

If you need further clarification or have questions, feel free to comment for additional assistance.

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

Update the function to be contained in a distinct JavaScript file - incorporating AJAX, HTML, and MySQL

Currently, I am working on a project and need to showcase a table from MySQL on an HTML page. The JavaScript function in my code is responsible for this task, but due to the Framework 7 requirement, I must separate the function into a different .js file ra ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

In Nodejs, there is a way to determine the size of a document stored

I have a question: How can I determine the size of a cursor, in terms of kilobytes (KB), without actually fetching it? I've come across various sources, such as this post on Stack Overflow, but I don't want to retrieve the query result just to f ...

Creating a JavaScript anchor through a backend bean function

Is it crazy to want to create an anchor that can be called from a backing bean method using JavaScript? I need to do this for specific reasons, utilizing a commandButton with ajax set to false. I'm attempting the following approach: RequestContext.g ...

Enhancing a Stripe customer object with additional metadata

While setting up a payment system using Stripe, I encountered an issue when trying to add metadata to the customer object. Specifically, I wanted to include my workspace id in the metadata property of the customer. However, upon executing the code below, I ...

Utilize a callback function without any arguments, and make use of the

After working on tutorials from nodeschool.io, I encountered a challenging problem related to streams. The provided solution had me puzzled. I'm particularly confused about the role of the upper variable and why it's necessary to use this.push. ...

Tips for rendering objects in webgl without blending when transparency is enabled

My goal is to display two objects using two separate gl.drawArrays calls. I want any transparent parts of the objects to not be visible. Additionally, I want one object to appear on top of the other so that the first drawn object is hidden where it overlap ...

The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths): This is my router code: import { createRouter, crea ...

``"Selecting a location upon clicking a marker in the array

I have limited experience with javascript but I am determined to improve my skills. Currently, I am facing a major roadblock in a project that I am working on and urgently require assistance. The project involves creating a map with marked locations from ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

JQuery GET brings back unnecessary HTML content

Currently utilizing a PHP cart class and implementing some jQuery to dynamically update a div when users add products. The issue I'm encountering is that upon adding a product, the list of products on the HTML page gets duplicated (see screenshot) ev ...

What are the reasons for a jQuery function to run in a selective manner?

There seems to be some inconsistency in the behavior of this incomplete script that I'm trying to debug. The issue arises when I click off an item, as sometimes the $(editObj).removeAttr('style'); line of code executes and other times it doe ...

Exploring ways to reach a specific digit level in JavaScript

As a newcomer to JavaScript, I've been searching online and trying different solutions but none have worked for me. Currently, I have a variable called num = 71.666666666 I'm looking to limit this number to 71.66 So far, I have attempted the f ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Is there a way to retrieve all the selected values from multiple select inputs when a button is clicked in React?

I am currently working on developing a questionnaire where the select inputs' values are collected and averaged to generate a final score. Although it may sound simple, I'm facing difficulties in retrieving these values. At this point, my primary ...

Guide on enabling automatic rotation using Javascript

Recently, I came across a slider online that unfortunately did not have an autorotate feature. Despite my attempts to add an autorotate function using setTimeout and click functions, I was unsuccessful. This particular slider contains 4 buttons for each s ...