What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the first data element is filled, it should recognize that the second element is empty and append the new data there.

<template>
  <input type="text" v-model="name">
  <input type="text" v-model="surname">
  <button @click="addCustomer"></button>
</template>

<script>
import Vue from "vue";

export default {
  data(){
    return{
      name:null,
      surname:null,
      customers:[{},{},{}],
      currentIndex:null
    }

  },
  methods:{
    addCustomer(){
      let findIndex = this.customers.findIndex((customer) => customer.name === this.name );
      let isInArray = findIndex !== -1;
      if(isInArray){
        Vue.set(this,"currentIndex",findIndex)
        Vue.set(this.customers[this.currentIndex], 'name', null)
    }else{
        // What content should be included here?
      }
    }
  }
}
</script>

Answer №1

Based on your query, to add a customer to the list if they are not already in the customers' list by name and update them if they exist, you can use the following code snippet.

Here is an example of how your code should look:

<template>
  <input type="text" v-model="name">
  <input type="text" v-model="surname">
  <button @click="addOrUpdateCustomer"></button>
</template>

<script>
import Vue from "vue";

export default {
  data(){
    return{
      name:"",
      surname:"",
      customers:[]      
    }

  },
  methods:{
    addOrUpdateCustomer() {
      const customerIndex = this.customers.findIndex(c => c.name === this.name);
      
      if(customerIndex > -1) {
        let existingCustomer = this.customers[customerIndex];
        existingCustomer.surname = this.surname;
        this.customers[customerIndex] = existingCustomer;
      }
      else {
        this.customers.push({name: this.name, surname: this.surname});
      }
    }
  }
}
</script>

Answer №2

It seems like there is a misunderstanding here. The `customers` array consists of empty objects, which may or may not contain your customers' information. However, creating empty objects as placeholders is not necessary. JavaScript arrays have various methods that can help you achieve your desired outcome. For example, you can use the push method to add an element at the end of the array or the slice method to remove it.

In your scenario, you could do something like this:

addCustomer(){
      let findIndex = this.customers.findIndex((customer) => customer.name === this.name );
      let isInArray = findIndex !== -1;
      if (!isInArray){
        this.customers.push("name", "Nacho")
      }
    }

If the customer is not already in the array, you would want to add them. If they are already in the array, the action to take will depend on your specific logic. However, you can remove them using the `slice` array method.

By the way, using the Vue.set method is unnecessary in this case, as the push method achieves the same result (Vue automatically handles the reactivity of the newly added value).

Answer №3

One user above mentioned that there may be a misconception at play here.

An array is essentially a list of customers, while an object holds the attributes of each customer. If the initial customer list is empty, there is no need to add objects unnecessarily.

For instance, if a cart needs 5 fruits and it is currently empty, there is no value in adding empty strings to the cart.

Likewise, if an array requires 5 numbers but is currently empty, there is no point in inserting placeholders like 0.

Attempting something like this is redundant:

const cart = ["", "", "", "", ""] 
const array = [0, 0, 0, 0, 0] 

This approach serves no purpose.

If you wish to limit the size of the array, you can terminate the function when the array reaches the desired length.

Here's an example:

// Stop the function when the array size reaches 3
// Indicates a size limit of 3
if (array.length === 3) return

const addCustomer = () => {
  if (array.length === 3) return
  array.push(value) // Replace 'value' with actual customer or item to be added
}

An example with your implementation (Composition API)

Example in Options API

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 the best way to utilize node exec in synchronous mode?

I have a scenario where I need to run exec synchronously. Is there an alternative method to achieve this without using the deprecated execSync library? Can bluebird promises be used for this purpose? for (var i = 0; i < testCasesLength; i++) { va ...

IBM Watson Conversation and Angular Integration

After recently diving into Angular, I am eager to incorporate a Watson conversation bot into my angular module. Unfortunately, I'm facing an issue with including a library in Angular. To retrieve the Watson answer, I am utilizing botkit-middleware-wat ...

Efficiently process 100 tasks per minute using a microservice architecture

I have a node.js application that needs to perform the following tasks: Retrieve zip files, extract them (containing JS module files with key-value pairs - usually 5-8 files per request) Analyze these files, create new ones from the analysis, and ...

Storing the translated value from angular translate into a global variable: a guideline

I've been grappling with this issue for quite some time now without much success. My goal: I'm attempting to store the value of an angular translation (using $translate) in a global variable so that I can later use it for assigning dynamic varia ...

How do I remove the scroll bar from the datagrid using Material UI?

https://i.stack.imgur.com/lM01l.png Is there a way to remove the scroll bar at the bottom of the page? I have already attempted using autoPageSize, but it did not solve the issue. Here is the link to the autoPageSize documentation. import { DataGrid } f ...

Encountering an issue with the message: "Property 'ref' is not available on the type 'IntrinsicAttributes'."

Having trouble implementing a link in React and TypeScript that scrolls to the correct component after clicking? I'm using the useRef Hook, but encountering an error: Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assi ...

Using VueJS to dynamically hide or show elements based on the selection made in a form

I'm facing a challenge with displaying device information based on selection from a form select element in Vue.js. I have an array of devices that I render using a v-for loop, but I can't figure out how to filter and display them according to the ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...

Superimpose a canvas onto a div element

I'm struggling to overlay a canvas on top of a div with the same dimensions, padding, and margins. Despite using position: absolute and z-index as suggested in similar questions, the canvas keeps appearing underneath the div. Here's my current co ...

Having trouble receiving JSON/JSONP correctly

I've been exploring the world of APIs and I'm facing a roadblock right at the beginning. My goal is to extract data from the Fever Public API in order to retrieve a list of subscribed RSS feeds. The API appears to be straightforward - check it ou ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

Chakra UI: How come the tooltip is appearing in the top left corner of the screen instead of directly above the element?

CreatedByModal is a unique chakra modal that incorporates tooltips. However, I am facing an issue where the tooltip appears at the top of the screen instead of directly above the icon when hovering over the icons. You can see in the image provided that the ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Obtain information from Firebase and display it in a list

I've been struggling to retrieve my to-do tasks from a firebase database, but unfortunately, no data is appearing on my view. Surprisingly, there are no errors showing up in the console. My journey led me to the point of "saving data" in firebase. H ...

Utilizing Vue to Customize Chart Settings with Data

I'm currently working on hitting a rest api to retrieve a dataset for a specific piece of equipment. However, I'm struggling to extract the first column of data as an array. I've attempted using computed and methods in vue, but I constantly ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

What is the best way to use JavaScript to emphasize a substring that includes a wild card character surrounded by two specific characters

In the dataframe below, I have multiple strings stored: v1 v2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE1 BRCTNIGATGATNLGATGHTGNQGTEEFR SEQUENCE2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE3 I am interested in searching for a ...

WARNING: No matches found in the MySQL database for the searched word

Exploring the realm of coding 1) Gathering data from MySQL via PHP 2) Transferring data from PHP to D3 based on input using a PHP URL. Want to trigger an alert when the text in the input field does not match any records in the MySQL database. Upon testi ...

React is throwing an error message stating that setCount is not a valid function

Getting an error saying setCount is not a function. I am new to this, please help. import React, { memo, useState } from "react"; export const Container = memo(function Container() { const { count, setCount } = useState(0); return ( ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...