How do you trim a string and display the final 3 characters?

When dealing with a list of objects, I want to ensure that the chain of tasks does not become too long and break the table or appear aesthetically unpleasing. Therefore, my goal is to trim the tasks and display only the last 3. In the image below, multiple tasks are shown. What I expect is:

data:[{tasks:"task 1 task 2 task 3 task 4}] where all tasks can be added, but I want to limit the display to the last 3 in order to prevent table disruptions.

<tr
          v-for="item in presupuestos"
          :key="item.id"
          :style="item.id === presupuestoSeleccionado.id && TheStyle"
        >
          <td>{{ item.tipoPresupuestoString }}</td>
          <td>{{ item.numero }}</td>
          <td>{{ item.cliente.nombre }}</td>
          <td>{{ formatDate(item.fechaEntrega) }}</td>
          <td>{{ item.presupuestoComentarioString }}</td>
          <td>{{ item.tareas }}</td>
        </tr>

getList() {
  const tipoPresupuesto =
    this.tipoPresupuesto != null ? this.tipoPresupuesto : "";
  const clienteId = this.cliente != null ? this.cliente.id : "";
  const procesoId = this.proceso != null ? this.proceso : "";
  const tareaId = this.tareaFiltro != null ? this.tareaFiltro : "";

  Swal.fire({
    title: "Espere unos momentos ...",
    showConfirmButton: false,
  });
  this.presupuestoServices
    .getListSupervisar(tipoPresupuesto, clienteId, procesoId, tareaId)
    .then((data) => {
      Swal.close();
      this.presupuestos = data;
      console.log(data)
      this.$data.TheStyle.backgroundColor = "#c3bbbb"; //Para seleccionar los row de algun color
    })
    .catch((error) => {
      Swal.close();
      this.showError(error.response.data);
    });
},

[HttpGet("getListSupervisar")]public async  
   Task<ActionResult<List<Presupuesto>>>
    GetListSupervisar([FromQuery] 
                                                           int? tipoPresupuesto, [FromQuery] int? clienteId, 
                                                     
                                [FromQuery] int? 
                         procesoId, [FromQuery] int? tareaId)
{
string[] _include = { nameof(Presupuesto.Usuario), 
    nameof(Presupuesto.Cliente), 
    nameof(Presupuesto.PresupuestoDetalle) + "." + 
    nameof(PresupuestoDetalle.PresupuestoDetalleProceso),
    nameof(Presupuesto.PresupuestoDetalle) + "." + 
    nameof(PresupuestoDetalle.ArticuloBp),
    nameof(Presupuesto.PresupuestoDetalle) + "." + 
    nameof(PresupuestoDetalle.ArticuloCamara),
    nameof(Presupuesto.PresupuestoTarea),
    nameof(Presupuesto.PresupuestoComentario)
};
var result = await _presupuestoServices.GetListAsync(a => a.Id > 0
                                                    && a.TipoPresupuesto!=null
                                                    && ((tipoPresupuesto == null && a.TipoPresupuesto != (int)Enumeraciones.PresupuestoTipo.Presupuesto) || a.TipoPresupuesto == tipoPresupuesto)
                                                    && (tareaId == null || a.PresupuestoTarea.Where(b => b.TareaId == tareaId).Count() > 0)
                                                    && (procesoId == null || a.PresupuestoDetalle.Where(b => b.PresupuestoDetalleProceso.Where(c => c.ProcesoId == procesoId && c.Cantidad < b.Cantidad).Count() > 0).Count() > 0)
                                                    && (clienteId == null || a.ClienteId == clienteId)
                                                    && a.PresupuestoDetalle.Count > 0
                                                    , _include);

var list = new List<Presupuesto>();

foreach (var presupuesto in result.ToList())
{
    //presupuesto.PresupuestoDetalle = presupuesto.PresupuestoDetalle.Where(a => a.EsPrimerCristal == true).ToList();
    presupuesto.Procesos = ArmarProcesosFaltantes(presupuesto);
    presupuesto.PresupuestoComentarioString = presupuesto.PresupuestoComentario.Count>0 ? presupuesto.PresupuestoComentario.LastOrDefault().Comentario : "";

    if (presupuesto.ImporteEnvio>0) 
    {
        presupuesto.PresupuestoDetalle.Add(new PresupuestoDetalle() { Descripcion = "Envio", Cantidad = 1, Ancho = 1, Alto = 1,Presupuesto = presupuesto });
    }
    if (presupuesto.ImporteDescuento > 0) 
    {
        var descuentoPorcen = (presupuesto.DescuentoExtraPorcen + presupuesto.Cliente.Descuento)/100;
        presupuesto.PresupuestoDetalle.Add(new PresupuestoDetalle() { Descripcion = "Descuento", Cantidad = 1, Ancho = descuentoPorcen, Alto = descuentoPorcen, Presupuesto = presupuesto });
    }
    if (presupuesto.ImporteColocacion > 0)
    {
        presupuesto.PresupuestoDetalle.Add(new PresupuestoDetalle() { Descripcion = "Colocacion", Cantidad = 1, Ancho = 1, Alto = 1, Presupuesto = presupuesto });
    }

}

return result;
 }


ENTITIES DE PRESUPUESTO
public string Tareas
{
get
{
    var result = "";
    foreach (var item in PresupuestoTarea.OrderBy(a=>a.FechaAlta))
    {
        result = item.Descripcion + " " + result;
    }
    return result;
}
 }
 [NotMapped]

Answer №1

I have crafted a solution based on the issue outlined in the initial two paragraphs, as delving into an entire codebase can be overwhelming.

To tackle this problem, you can utilize the computed property to extract and display only the last three elements from an array.

Here is a Live Demo showcasing the implementation:

new Vue({
  el: '#app',
  data: {
    originalObject: [{
      id: 1,
      tipoPresupuestoString: 'tipoPresupuestoString 1',
      numero: 'Numero 1',
      fechaEntrega: 'fechaEntrega 1',
      presupuestoComentarioString: 'presupuestoComentarioString 1',
      tareas: 'tareas 1',
      cliente: {
        nombre: 'nombre 1'
      }
    }, {
      id: 2,
      tipoPresupuestoString: 'tipoPresupuestoString 2',
      numero: 'Numero 2',
      fechaEntrega: 'fechaEntrega 2',
      presupuestoComentarioString: 'presupuestoComentarioString 2',
      tareas: 'tareas 2',
      cliente: {
        nombre: 'nombre 2'
      }
    }, {
      id: 3,
      tipoPresupuestoString: 'tipoPresupuestoString 3',
      numero: 'Numero 3',
      fechaEntrega: 'fechaEntrega 3',
      presupuestoComentarioString: 'presupuestoComentarioString 3',
      tareas: 'tareas 3',
      cliente: {
        nombre: 'nombre 3'
      }
    }, {
      id: 4,
      tipoPresupuestoString: 'tipoPresupuestoString 4',
      numero: 'Numero 4',
      fechaEntrega: 'fechaEntrega 4',
      presupuestoComentarioString: 'presupuestoComentarioString 4',
      tareas: 'tareas 4',
      cliente: {
        nombre: 'nombre 4'
      }
    }, {
      id: 5,
      tipoPresupuestoString: 'tipoPresupuestoString 5',
      numero: 'Numero 5',
      fechaEntrega: 'fechaEntrega 5',
      presupuestoComentarioString: 'presupuestoComentarioString 5',
      tareas: 'tareas 5',
      cliente: {
        nombre: 'nombre 5'
      }
    }]
  },
  computed:{
    presupuestos() {
      return this.originalObject ? this.originalObject.slice(-3) : this.originalObject
    }
  }
})
table, td {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <tr
        v-for="item in presupuestos"
        :key="item.id"
        >
      <td>{{ item.tipoPresupuestoString }}</td>
      <td>{{ item.numero }}</td>
      <td>{{ item.cliente.nombre }}</td>
      <td>{{ item.fechaEntrega }}</td>
      <td>{{ item.presupuestoComentarioString }}</td>
      <td>{{ item.tareas }}</td>
    </tr>
  </table>
</div>

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

Vue JS Issue: Button click does not trigger tooltip update

I am currently utilizing Vue 3 alongside Bootstrap 5.2. In my project, I have successfully implemented a tooltip by the following method: App.vue <script> import { Tooltip } from "bootstrap"; export default { mounted() { Array.from( ...

Utilize a variable within the res.writeHeads() method in Node.js

Greetings all. I have encountered an issue that I need help with: Currently, I am using this block of code: res.writeHead(200, { "Content-Length": template["stylecss"].length, "Connection": "Close", "X-XSS-Protection": "1; mode=block", "S ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Switch between display modes using a button and CSS media query

I'm trying to find the most effective method for toggling display states on a webpage using a button while also being able to adjust based on screen size. For larger screens, I want to default to a horizontal layout with the option to switch to vertic ...

A Guide on Integrating a Javascript Reference into HTML while Displaying a PHP Object

Our website relies heavily on PHP modules to generate objects that are essential for constructing our web pages. Some of the key modules we have include: Anchor (ahref) Button CheckBox ComboBox DateTime Email Label Note Password Phone RadioButton RichTe ...

Adding multiple variables in jQuery: A guide to mimicking the .= operator from PHP

Being new to jQuery, I'm a bit unsure of how to achieve this. Typically in php, I can accomplish something like this: $result = ''; $result .= 'Hi'; $result .= ' there'; echo $result; I'm simply wondering if there ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

What is the best way to incorporate external scripts into a Node.js project?

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> What is the process for adding an external library to a node.js application? I am seeking assistance on how to integrate the following library into my ...

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

How can I pass a string value from C++ to JavaScript in a Windows environment using Visual Studio 2008?

In my current project, I have successfully implemented an IDL for passing a string value from JavaScript to C++. The JavaScript code effectively passes a string value to the C++/COM object. [id(1), helpstring("method DoSomething")] HRESULT DoSomething([in ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Utilizing the OrientDB HTTP API within an Angular platform - a comprehensive guide

When trying to query OrientDB from an Angular service method, authentication-related errors are encountered. It appears that two GET requests are required for successful querying of OrientDB. An Authentication call: Requesting http://localhost:2480/conne ...

Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row. var myMatrix = []; var rows = 5; var columns = 3; for (var i = 0; i < rows; i++) { var temp = 1; myMatrix[i] = [i]; for (var j = 0; j < columns; j++) ...

Tips for including a Places Autocomplete box within an InfoWindow on Google Maps

I am currently working with the Google Maps Javascript API v3 and I am facing a challenge. I want to integrate a Places Autocomplete box inside an InfoWindow that pops up when a user clicks on a marker. I have successfully created an autocomplete object a ...

Launching my initial React application

After creating a small React app using the boilerplate available at https://github.com/vasanthk/react-es6-webpack-boilerplate I was able to run it smoothly on my localhost. However, I am now facing confusion on how to configure it for live deployment. F ...

Unable to open javascript dialog box

One issue I encountered involves a jqGrid where users have to click a button in order to apply any row edits. This button is supposed to trigger a dialog box, which will then initiate an ajax call based on the selected option. The problem lies in the fact ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Resetting the internal state in Material UI React Autocomplete: A step-by-step guide

My objective is to refresh the internal state of Autocomplete, a component in Material-UI. My custom component gets rendered N number of times in each cycle. {branches.map((branch, index) => { return ( <BranchSetting key={ind ...

Experiencing difficulties when integrating the pdf-viewer-reactjs module within Next.js framework

I recently integrated the pdf-viewer-reactjs library into my Next.js project and encountered the following error: error - ./node_modules/pdfjs-dist/build/pdf.js 2094:26 Module parse failed: Unexpected token (2094:26) You may need an appropriate loader to h ...

Vue application experiencing never-ending update cycle following array assignment

Here is the JavaScript code I am working with: const storage = new Vue({ el: '#full-table', delimiters: ['[[', ']]'], data: { events: [], counter: 0, }, methods: { eventCounter: fu ...