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

Creating a custom ID for a Firebase POST request

Is it possible to assign a custom ID in Firebase when using the POST method? For example: { "users": { "user_one": { "username": "jdoe", "password": "123" } } } I'm currently working on a Vue.js project and I want to save ...

Leverage arrays within a personalized filtering system

I have created an array with the structure shown below... $scope.myArr = [arg1, arg2]; Now, I am interested in developing a custom filter that will accept this array as input and compare it to another array. For instance, I intend to use it in the follow ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

Creating a JavaScript function in Selenium IDE specifically for today's date

Just starting out with Selenium IDE and looking to build a set of regression scripts for our department. Trying to insert today's date plus 180 days into a field using a JavaScript function. If anyone can guide me on how to write this function, I wou ...

Is it possible to use JavaScript to click on a particular point or element within a canvas?

Is there a way to trigger a click at a specific point on a canvas without direct access to the code that generates it? I've attempted using coordinates, but haven't had any success. Any alternative suggestions would be appreciated. UPDATE: To pr ...

Tips for inserting a blank space into a text box

It feels like such a simple issue, but my function is incorrectly returning "1" instead of just an empty space "" in my textbox. <td><input type="button" value="Space" name="Space" onClick='document.firstChild.search.value = document.firstCh ...

Using a JavaScript array in Java

Currently, I am working on an Android app that requires me to download data from a JavaScript array representing the schedule for my school. The link to the data is here. I am looking for a way to parse this data into a Java array. I have considered using ...

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

Invoke the javascript function by referencing the JavaScript file

I'm encountering an issue with two JavaScript files. One file uses the prototype syntax, while the other utilizes jQuery. Unfortunately, they don't seem to work harmoniously together. I've attempted calling the functions within the files usi ...

The system detected a missing Required MultipartFile parameter in the post request

Can anyone explain to me why I am encountering the error mentioned above? I am unable to figure out the reason. Below is my code, please review it and suggest a solution for fixing this error. The objective is to upload multiple files to a specific locatio ...

Tips for delaying my response in nodejs until the loop is complete

This is the code I'm currently working with: myinsts.forEach(function (myinstId) { Organization.getOrgById(myinstId,function (err, insts) { res.json(insts); }) }); I am using Node.js and encountering an error message that says "Can't set hea ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

What could have caused these errors, since they never made an appearance?

'Link' component cannot be utilized within JSX. The type 'ForwardRefExoticComponent<LinkProps & RefAttributes<HTMLAnchorElement>>' is not a valid element for JSX. The type 'ForwardRefExoticComponent<LinkPro ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

Generate dynamic DIV elements and populate them with content

Can you assist me in getting this code to function properly? My goal is to dynamically create elements inside a div and fill each element with a value fetched from the database through a server-side function. I'm unsure if there's a better approa ...

Discover the power of Shopware 6 with the sw-inherit-wrapper feature for the sw-snippet-field and sw-media-field components in Vue.js

Currently, I am developing a custom administration module (plugin configuration) in Shopware 6 using Vue.js. An issue I am facing is the absence of an inherit wrapper that appears when there is a change in the sales channel. My goal is to replicate the s ...

Analyzing various field data collectively

Is there a way to use jQuery to compare multiple input field values and trigger an alert message saying 'There are similar values' if any match is found? <input value="111"> //similar <input value="222"> <input value="111"> //s ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...