Exploring the wonders of nested object destructuring in ES6

How have you been? I want to remove the property "isCorrect" from a nested object.

Original List

    id: 1,
    questionText: 'This is a test question for tests',
    answerOptions: [
      {
        answerText: 'A',
        isCorrect: true
      },
      {
        answerText: 'B',
        isCorrect: false
      }
    ],
    difficulty: 1
  },
  {
    id: 2,
    questionText: 'This is another test question for tests',
    answerOptions: [
      {
        answerText: 'A',
        isCorrect: false
      },
      {
        answerText: 'B',
        isCorrect: true
      }
    ],
    difficulty: 2
  }

Expected result

    id: 1,
    questionText: 'This is a test question for tests',
    answerOptions: [
      {
        answerText: 'A'
      },
      {
        answerText: 'B'
      }
    ],
    difficulty: 1
  },
  {
    id: 2,
    questionText: 'This is another test question for tests',
    answerOptions: [
      {
        answerText: 'A'
      },
      {
        answerText: 'B'
      }
    ],
    difficulty: 2
  }

I was able to achieve this using the delete code below but I believe there could be a better approach

const cleanResponses = (questions: Question[]): Question[] => {
  questions.forEach(question => {
    question.answerOptions.forEach((answer) => {
      delete answer.isCorrect
    });
  })

  return questions;
}

I tried the line below but it didn't work as expected :(

const { answerOptions: [{ isCorrect }], ...rest } = question

Thank you

Answer №1

When utilizing Array#map:

const arr = [
  { id: 1,
    questionText: 'This is a sample question for demonstration purposes',
    answerOptions: [ { answerText: 'A', isCorrect: true }, { answerText: 'B', isCorrect: false } ],
    difficulty: 1
  },
  {
    id: 2,
    questionText: 'This is another sample question for demonstration purposes',
    answerOptions: [ { answerText: 'A', isCorrect: false }, { answerText: 'B', isCorrect: true } ],
    difficulty: 2
  }
];

const res = arr.map(({ answerOptions = [], ...elem }) => ({
  ...elem, 
  answerOptions: answerOptions.map(({ isCorrect, ...answer }) => answer)
}));

console.log(res);

Answer №2

Whether you intend to mutate the current array or create a new one will determine the approach you take. Your code works well if you aim to modify the existing array (see the updated version below). However, if you prefer creating a new array, Majed Badawi has provided a solution using the map function. In any case, you will need to iterate over both the objects in the data array and the objects in the answerOptions array to achieve the desired outcome.

const array = [{id:1,questionText:"This is a test question for tests",answerOptions:[{answerText:"A",isCorrect:!0},{answerText:"B",isCorrect:!1}],difficulty:1},{id:2,questionText:"This is another test question for tests",answerOptions:[{answerText:"A",isCorrect:!1},{answerText:"B",isCorrect:!0}],difficulty:2}];

for (let { answerOptions } of array) {
  for (let obj of answerOptions) {
    delete obj.isCorrect;
  }
}

console.log(array);

Answer №3

Exploring a more detailed approach to achieve the desired result, we start by iterating over all objects in the array test from the outermost layer. The rest operator is used to distinguish the array of answerOptions objects from the other properties of the question. Moving forward, we proceed to iterate over the answerOptions array, utilizing the rest operator to construct a new answerOption object that excludes the isCorrect property. Finally, all components are merged back together. The function returns an object containing the separated question properties along with the updated answerOptions objects devoid of isCorrect.

  const test = [
    {
      id: 1,
      questionText: "This is a test question for tests",
      answerOptions: [
        {
          answerText: "A",
          isCorrect: true
        },
        {
          answerText: "B",
          isCorrect: false
        }
      ],
      difficulty: 1
    },
    {
      id: 2,
      questionText: "This is another test question for tests",
      answerOptions: [
        {
          answerText: "A",
          isCorrect: false
        },
        {
          answerText: "B",
          isCorrect: true
        }
      ],
      difficulty: 2
    }
  ];

  const cleanResponses = (questions) => {
    return questions.map(({ answerOptions, ...rest }) => {
      const newAnswerOptions = answerOptions.map((answerOption) => {
        const { isCorrect, ...newAnswerOption } = answerOption;
        return newAnswerOption;
      });
      return { answerOptions: { ...newAnswerOptions }, ...rest };
    });
  };
  
  console.log(cleanResponses(test))

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

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

Issue with alert not being triggered in browser when using HTML and JavaScript function

Just starting out with HTML and Javascript! I'm working on a simple program where users can input a card number, and the browser should indicate whether it is valid (between 13-16 digits) or not. The website looks great, but I'm not getting an ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

Attempting to control an array of objects

In my current records: The parts with IDs 14.3, 14.2, and 14.1 belong to part ID = 30. The goal is to achieve the following: 1) By default, the first two IDs will be selected. If a user tries to select ID = 71, which belongs to part 30, they should not ...

Acquiring a snippet of JSON data from a Python response

As a newcomer to the world of programming, I am currently working on using an API to automate various tasks. While I have successfully managed to get a response from the API, my focus is specifically on extracting just two values - the host and port. Bel ...

Using Angular 4 to transfer data from a dynamic modal to a component

Currently implementing material design, I have set up a dialogService for dynamically loading MdDialog. My goal is to create a search dialog with filters that, upon submission, directs the user to a search-results component route. However, I am struggling ...

Jquery problem with creating a cascading dropdown list

I recently came across a tutorial that provided code for creating cascading dropdown lists using JQuery. I attempted to implement this code in my own project but encountered some issues. public class IndexViewModel { //1st dropdown list ID ...

What sets apart Selenium's mouseMove() function from the physical movement of a mouse?

Imagine I have element A and element B on a webpage. Using tools like Selenium or PhantomJS, I can manipulate the mouse via coordinates. By identifying the position of element A (a link) and element B (a submit button), I can create a bezier curve or mimi ...

Guide to attempting an asynchronous function again in JavaScript with a time delay

I've been facing a challenge while trying to retrieve a record from a database. The issue of race conditions often leads to situations where the record might not be available when attempting the initial fetch. How can I implement retry logic to overco ...

Display various messages when submitting a form based on Ajax technology

I have been working on a script that utilizes AJAX to process form submissions. While I can successfully submit the form using AJAX and display a success message, I am looking to customize the messages based on the background data processing of the form. ...

What is the method for adding 24 hours to a 12-hour timestamp while preserving the AM and PM designation?

I have created the following code to display real-time, but I am struggling with adding a timestamp that switches from 24-hour format to 12-hour format with AM and PM. setInterval(function() { var date = new Date(); var hours = date.getHours(); va ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...

Try logging in again if an error occurs

I've encountered some failing tests that we suspect are caused by network drops. To address this problem, I have modified my login method to retry after an error is detected. I would also like to have the number of retry attempts displayed in the cons ...

What is the best way to retrieve values within a nested JSON array using PHP?

My goal is to retrieve a specific value from a nested JSON structure using PHP. After conducting a print_r() function, I obtained the following data: Array ( [types] => Array ( [0] => Array ( ...

I could use some assistance with deciphering JSON data

After using console.log to display the data I received, I observed an object structured as follows (I trimmed some details for clarity and used ... to indicate repetitive information): [ Submission { title: 'Untitled', content: { ur ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

What is the method for triggering two actions within a single linked tag?

I have a link tag structured like this: <a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a> Upon clicking the "Home" link, it should navigate to the dashboard. At the dashboard page, I want to check i ...

Is there a substitute for the Javascript onchange event listener in CakePHP 3?

Having trouble with the javascript onchange event listener in cakephp3.7. I've got an e-commerce web app running smoothly on cakephp3.7. Now, I want to improve the sales submission form by dynamically loading extra fields based on the product category ...