What is the best way to delete a property from an object in an array?

I have a Vue component with an array that includes IDs which I want to remove while keeping the other elements intact. Is there a way to achieve this within a method?

Is it possible to filter out the ID index from the array using Vue methods?

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options;
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>

Answer №1

To iterate over the array and generate a new array of names

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options.map(option => {
        return { 
          option: option.option
        }
      });
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>

Answer №2

If you want to extract names using the map method, you can do it as follows:

var vm = 
new Vue({
  el: "#app",
  data: {
    options: [
      {id:100, option:"1 - John Doe"},
      {id:200, option:"2 - Jane Doe"}
    ]
  },
  methods: {
    getNames(){
      
      let names = this.options.map(o => o.option);
      
      console.log(names);
    }
  }
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="getNames()">TEST</button>
</div>

Answer №3

This task focuses on utilizing pure JavaScript without relying on VueJS or any other framework.

There are two main approaches that can be taken: preserving necessary elements or eliminating unnecessary ones:

  1. map: used to convert each original element into a new format and produce a new array
  2. forEach with delete: employed to remove unwanted properties from the existing array
let options: [
  {id:100, option:"1 - John Doe"},
  {id:200, option:"2 - Jane Doe"}
];

// creating a new array of strings
let strings = options.map(o => o.option);
console.log(strings);

// modifying the original array by deleting a specific property
options.forEach(o => delete o.id);
console.log(options);

For further reference: Remove property for all objects in array

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

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...

Choose the text that appears in the input or textbox field when tapping or clicking on it

Desperately Seeking a Clickable Textbox The Quest: In search of a cross-browser textbox/input field that can select its content on click or tap. An elusive challenge haunting developers for years. The Dilemma: Using a touch device triggers the tap e ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

Error occurred due to a reference to a function being called before it was

Occasionally, I encounter a "Reference Error" (approximately once in every 200 attempts) with the code snippet below. var securityPrototype = { init: function(){ /* ... */ }, encryptionKey: function x() { var i = x.identifier; ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...

Encountered the error "Unable to update state on unmounted component in React because of timeout"

Despite the abundance of information available online about this particular warning, I am still struggling to find a solution that applies to my specific scenario. Currently, I am developing an autosave feature for a form component where typing triggers a ...

Unlocking the Secrets of Launching a Modal with Javascript

I currently have an HTML code that includes a fabulous floating button. When I click on this button, I would like to open a modal popup window but unfortunately, I am unsure of how to achieve this. index.html <html> <head> <link rel="s ...

Struggling with uploading a Vue project to Github Pages

I attempted to deploy my vue-cli project on Github Pages by following the guidelines provided on a website and on GitHub's support page. To deploy vue-cli to Github Pages, refer to this link: https://medium.com/@mwolfhoffman/deploying-to-github-pages ...

The value returned is undefined when using getStaticProps

Recently, while working on my project with Next.js, I encountered an issue where I was trying to access data but kept getting undefined. Below is the code snippet that I was working with: function Home({books}) { console.log(books) return <div>Home ...

Unable to display the string following a space in the value attribute of an hbs file

<input type="text" class="form-control" id="exampleInputEmail2" name="productName" value={{product.productName}} > When I input 'Smart Phones' into product.produc ...

Concealing categories within an accordion-styled menu

Recently, I put together a list that includes various pieces of information along with an accordion menu. Take a look at the list However, I've encountered a small issue which has left me quite perplexed. When a menu item is clicked - for instance, ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Establish validation parameters for uploading multiple files

I need to implement client-side validation for my FileUpload control to ensure that users can only select up to 10 images. While I already have the server-side code in place, I now want to add client-side validation as well. Sample Code: <asp:FileUplo ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

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 ...

I want the name of the hospital to be displayed in the dropdown menu with a shortened version of the hospital's name appearing

Check out my code snippet: here import Autocomplete from "@mui/material/Autocomplete"; import TextField from "@mui/material/TextField"; import React, { useState } from "react"; const hospitalList = { docs: [ { _id: ...