Best practices for returning values from VueJS computed properties

I've been using this code repeatedly. I wonder if there is a more efficient way to create this shortcut

Take a look at the following example

// items.js

export default [
  { title: 'ABC', href: 'javascript:void(0)' },
  { title: 'DEF', href: 'javascript:void(0)' }
]
// index.vue

<script>
import items from './items.js'
export default: {
  computed: {
    links() {
      let results = []
      items.forEach((item,index) => {
        item.id = index

        results.push(item)
      })
      return results
    }
  }
}
</script>

//resulting object = {title: 'ABC', href: 'javascript:void(0)', id: 0}

I just want to add an id property to each object in the computed property, so that I don't have to worry about using

v-for="(item, index) in items" :key="index"
. Instead, I can use
v-for="item in links" :key="item.id"
in the template

The question:

  1. In the code, I declare an empty array called results let results = [], then populate it with data using forEach before returning the result. Is there a better way to return each looped data without declaring an empty array and populating it before returning the generated data?

  2. Sometimes I not only add an id, but maybe also other properties like item.internal = true, or levels if it's multilevel.

Answer №1

To include an id in each item, you can make use of the map function along with the spread operator within a computed property:

 computed: {
    updatedItems() {
       return  originalItems.map((item,index)=>({id:index,...item}))
    }
  }

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

Make sure that JSON.stringify is set to automatically encode the forward slash character as `/`

In my current project, I am developing a service using nodejs to replace an old system written in .NET. This new service exposes a JSON API, and one of the API calls returns a date. In the Microsoft date format for JSON, the timestamp is represented as 159 ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

Is there a way to deactivate a submit button that is delivered through an Ajax response within a div (popup)?

I have a button that triggers an AJAX request when clicked, opening a popup div with the Ajax response displayed inside. The popup is essentially a form with text boxes and a submit button. I've been attempting to add some JavaScript validations, but ...

Replacing parts in Vue when clicking on an element

I am currently working on a website with a storytelling concept. The idea is that when a user clicks on a certain element, a new layout will be shown - either a full-screen video or an image. After clicking the "next" button, a different content should be ...

Getting a 404 error when attempting to go straight to a URL in a Single Page Node App

Currently, my setup involves a NodeJS backend connected to a ReactJS frontend (without utilizing create-react-app). To bundle both the React frontend and the Node backend, I am using webpack. The webpack configuration generates an "dist" directory in the ...

The table is not visible when using Bootstrap Vue

Can anyone help me with displaying a table of flowers? I am having trouble making it show up on my page. Not quite sure how to use my data to get the flowers to display properly. Any guidance or advice would be greatly appreciated. <b-table> ...

Looking for a new slider option to replace the traditional Conveyor belt slideshow?

I have successfully used the Conveyor belt slideshow script from http://www.dynamicdrive.com/dynamicindex14/leftrightslide.htm. Now, I am looking to find another script that works similar to this one. Does anyone have any recommendations for a tool that ...

Having trouble with JavaScript syntax or encountering issues while utilizing THREE.ImageLoader in a loop in three.js?

It seems like more of a JavaScript syntax issue than a Three.js problem, but I'm stuck. I have an object called "o = {}", with textures stored in this format: o = { ... textures: { one: { low: { t: new THREE.Texture(), u ...

What is the best way to adjust the height and width of an mp4 video in Internet Explorer?

I came across a code snippet that looks like this video { object-fit:fill; } <!DOCTYPE html> <html> <body> <video width="800" height="240" controls> <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4" ...

Use Javascript or jQuery to traverse a tree in postorder and generate HTML markup

I am looking to generate HTML code similar to the following: <ul> <li>Submenu 1 <ul> <li>Submenu 1.1</li> <li>Submenu 1.2 <ul> <li>Subm ...

Displaying and hiding collapsible items in Bootstrap 4: A guide to showing one item at a time

I'm working on collapsible menus and I need them to completely hide when one is clicked, instead of just collapsing. This behavior is different from an accordion setup. To achieve this, I incorporated the following function into my code: $('#bo ...

Using multiple serializers to serialize an array in Rails serializer

After processing, I am receiving an array. gem 'active_model_serializers' Now, my goal is to utilize a serializer to transmit data in json format. However, when I invoke the serializer, it fails to retrieve the object due to being an Array. C ...

Is there a way to add a class (1) when scrolling to a specific div, and then switch from class (1) to class (2) when moving away from the

How can I create a JavaScript function that adds the class "animated fadeInDown" to div id hover1 when I reach or scroll to it? Also, when I scroll down or leave div id hover1, how do I change the class from "animated fadeInDown" to "animated fadeOutUp"? ...

Change the JavaScript code to output HTML rather than just plain text

I've created a small plugin for tinymce4 that adds an additional dropdown menu with a list of headers (e.g. h1, h2...). The issue I'm facing is that I'm trying to display these header elements with their corresponding styles (e.g. <h1> ...

The error message in the lang.js file on line 21 says: "There is a Syntax

https://i.sstatic.net/mLrvW.png Here's my package.json file: "ng2-file-upload": "1.0.3", "ng2-translate": "2.5.0", "angular2-cookie": "1.2.3", "angular2-google-maps": "0.15.0", "key-codes": "0.0.1", "rxjs": "5.0.0-beta.12" "@angular/common": "2.0.0" ...

Retrieve all elements from an array that has been imported through the fs module

To extract the values from the array jsonParsed.students[actStudent].evnetsPartaken, which may look like [1,2,0] (note: check attachments for full data), I need a way to reference each value in correlation to the event number in the configEvents JSON array ...

Tips for extracting both the div and entire inner content using JavaScript

I need to retrieve the inner content of a div using JavaScript For example: <div id="content" style="height: 20px; overflow: hidden"> content<br>content<br>content<br> </div> This is my HTML code. I only know the div&apos ...

The correct usage of && and || operators in javascript

I've developed a small web application and I'm facing an issue where I want to trigger an alert when the 'enter' key is pressed if there is an empty or space value. Currently, the alert appears not only on hitting 'enter' but ...

Can someone show me the method to retrieve the book title based on a particular ID using linqjs?

I am working with a JavaScript array that contains objects including an id and book title. My goal is to search this array and retrieve the title based on a given id, preferably using linqjs. For example: "213-46-8915" : id "The Busy Executive's ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...