What is the best way to exclude a specific key when adding JSON objects to an array?

I'm facing a challenge with a JSON array of objects that contains other arrays of objects. The structure of this array is not fixed, making it difficult for me to delete specific elements like

delete mainArray[0].obj.subobj[1].objToOmit;

In my program, I need to exclude a key/object named possibleAnswers. While transferring the contents of one array to another, I must ensure that the possibleAnswers object is not included.

Is there a function or method that can help me search through an array of objects and omit the necessary key? What would be your solution?

Example :

Here is a minimal example: Edit: In the above JSON there is a key called possibleMembers which is wrong. its possibleAnswers

            var collectObservationsFromConceptSets = function () {
            $scope.consultation.observations = [];
            _.each($scope.consultation.selectedObsTemplates, function (conceptSetSection) {
                if (conceptSetSection.observations) {
                    _.each(conceptSetSection.observations, function (obs) {
                        $scope.consultation.observations.push(obs);
                    });
                }
            });
        }

While pushing the object into another array in the code above, how can I exclude the possibleAnswers keys? Is there a way to do this?

Thank you all for your assistance! Both answers provided are correct and yield the expected output. However, I can only select one answer as correct, and it will be chosen randomly.

Answer №1

Here is an interesting method that utilizes _.transform() to recursively omit specific keys from an array:

const recursiveKeyOmission = (keys, obj) => _.transform(obj, (acc, v, k) => {
  // If the key matches those in 'keys', skip it
  if(keys.includes(k)) return;
  
  acc[k] = _.isObject(v) ? recursiveKeyOmission(keys, v) : v;
});

const dataset = [{"observations":[{"possibleAnswers":[],"groupMembers":[{"possibleAnswers":[]},{"groupMembers":[{"possibleMembers":[]},{"possibleMembers":[]}]}]}]},{"observations":"Same as above"},{"observations":"Same as above"}];

const result = recursiveKeyOmission(['possibleAnswers'], dataset);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Answer №2

To eliminate all occurrences of 'possibleAnswers' from your original array, simply use the function

removeKey(arr, 'possibleAnswers')

function removeKey(objOrArr, keyToRemove) {
  if (Array.isArray(objOrArr)) {
    objOrArr.forEach(o => removeKey(o, keyToRemove));
  } else if (typeof objOrArr === 'object') {
    delete objOrArr[keyToRemove];
    Object.values(objOrArr).forEach(v => removeKey(v, keyToRemove));
  }
}

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

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

The Jquery Object #<Object> does not have the 'getElement' method available

I've been attempting to set up this table, following the instructions here: Despite verifying that my browser is correctly pulling the CSS and .js files, I keep encountering an error related to my sortabletable.js file. (screenshot of the error) htt ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

Using ng-repeat-start and ng-repeat-end in AngularJS along with nested ng-repeat

Hello, I have successfully implemented ng-repeat-start and end in a simple use case. However, I am facing an issue when trying to add an inner ng-repeat within the code snippet below: <tr ng-repeat-start="obj in rows" > <td ng-repeat="e in obj. ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

Guide on utilizing the carousel component in Bootstrap and populating it with data generated from Node.js

My goal is to design a carousel that displays 5 different pieces of information pulled from a separate app.js file. I attempted to implement a forEach loop, but encountered issues when trying to create a second Bootstrap carousel container. Here's th ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Unable to access an HTML element using refs within the render() method

Currently, I am working on developing a graphics editor using ReactJS. One of the main components in my project is the Workspace component. This particular component is responsible for drawing objects on the canvas element. The Workspace component is imple ...

What could be causing the absence of ReactDOM in my hello world application?

I have recently started learning Reactjs and I'm attempting to run a hello world program in the browser. However, I encountered an error which reads: react-dom.min.js:12 Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_ ...

The Checkboxlist generated by jQuery-Ajax does not function when clicked on

I have a dynamic radio button list (rblCategories) that, when the selected value changes, triggers the creation of a checkbox list using ajax and populates it. However, I am facing an issue with updating my datatable when any checkbox is checked/unchecked ...

User is automatically logged in upon account completion

Is there a way to improve user experience in my app by implementing Firebase authentication so that: Users do not need to log in again after creating an account Users are automatically logged in after creating an account To achieve this, I am follow ...

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

The chart appears oversized in the vue js. How can I make it smaller in size?

I recently integrated a line chart from Chart JS into my Vue.js project, but the chart is taking up too much space on my webpage. I'm looking for ways to make it appear smaller and more compact. This is my first time working with charts in Vue.js, so ...

Generate JSON samples for RESTful APIs automatically

I have successfully implemented RESTful APIs using Jersey 2.17 with Jackson in JSON format. Now, I am looking to create comprehensive RESTful Docs with JSON samples for developers. In my search for the right tool, I first experimented with the ServiceDoc ...

What is the method for implementing conditions within a button element in Vue.js 2?

Here is an example of my component code: ... <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> ... <script> import { mapGetters } from 'vuex' export default{ ...

Looping through a set of API calls using JavaScript Web API

Currently, I am in the process of developing an application using angularjs and ionic. Within this app, I have an array containing IDs, and my objective is to retrieve their corresponding names. To achieve this, I attempted the following code snippet: var ...

Tips on retrieving a dataset from Json when the element is variable

I'm looking for assistance with extracting a specific node from a JSON object in my WebApi. The structure of the JSON object can vary, but I know that it will contain a node with the following properties: "data": { "mop": & ...

Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service. Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] H ...