Tips for creating a nested array in Javascript:

Given the following:

var person = {name: "", address: "", phonenumber: ""}

I am trying to implement a loop to gather user input (until they choose to stop inputting information by entering nothing or clicking cancel). My goal is to utilize the person object as a prototype.

The objective is to create an object that can store the name, address, and phone number of multiple individuals. My approach involves dynamically adding an array to an object in each iteration of the loop. Here is a snippet of my code:

var person = {name: "", address: "", phonenumber: ""}
var customer = []; //used to store each person


var input = "x";

//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
  var input = prompt("Input separated by commas"); 
  //example input: mike, main, 123456789

  var results = input.split(", "); //create an array from the input

  //move input into the person array. 
  //person to look like {name = "mike", address = "main", phone = "123456789"}
  person.name = results.shift();
  person.address = results.shift();
  person.phone = results;


  customer[i] = person;//store the person array into the customer array.
}  

I've been attempting to dynamically generate and access something like this:

customer = 
[{name, address, phone}, 
{name, address, phone}, 
{name, address, phone}]

However, I am encountering errors when trying to access and print the data. When I use

console.log(customer[0].phone);

it seems like there is nothing stored in customer[0].phone and it does not produce an output.

Upon further investigation, I discovered that I cannot access the data I collected from user inputs. When attempting to print or display the customer array, I receive messages like [object Object] without the actual data.

Answer №1

  let clients = [];//initialize an empty array
  let person = {};// initialize an empty object
  let input = prompt("...");//prompt the user for input
  let results = input.split(", "); //create an array from the input
  person.name = results[0];//assign the first value to the name property
  person.address = results[1];//assign the second value to the address property
  person.phone = results[2];//assign the third value to the phone property
  clients[0] = person;//add the person object to the clients array.

The code above should meet your requirements. It is important to avoid using repeated prompts for the same user. Instead, consider using a form for smoother user experience. Additionally, be cautious of creating infinite loops like the one in your for loop condition.

Here is a jsfiddle link for your reference: http://jsfiddle.net/zkc2swmp/1/

Improvements can be made to this code, such as implementing if conditions and integrating it with a form. Feel free to try it out and suggest any changes or ask for further assistance.

Answer №2

  1. Initially, when you assign a person to a customer i.e. customer[i] = person; all other objects are inadvertently altered because the breaking point is set to input== "", causing all objects to be modified with null values.

  2. At the beginning, you define the property as "phonenumber" but then later you assign a value to "phone".

The corrected code should be:

var customer = []; // array to store each person
var input = "x";

// loop to prompt user for name/address/phone number input
for(var i = 0; input != ""; i++){
    var input = prompt("Input separated by commas"); 
    // example input: mike, main, 123456789

    var results = input.split(", "); // creating an array from the input
    var person = {};
    person.name = results.shift();
    person.address = results.shift();
    person.phone = results;
    customer[i] = person; // storing the person array into the customer 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

How can one utilize electron's webContents.print() method to print an HTML or text file?

Electron Version : 2.0.7 Operating System : Ubuntu 16.04 Node Version : 8.11.1 electron.js let win = new BrowserWindow({width: 302, height: 793,show:false}); win.once('ready-to-show', () => win.hide()); fs.writeFile(path.join(__dirname ...

Unable to conceal the innerHTML once the error has been rectified

My error messages are displayed using innerHTML. How can I make them disappear once the error is corrected? Currently, they stay on, even after the error is fixed. I tried resetting them at the top of the script but it didn't work. Link to JSfiddle ...

Dealing with interstitial advertisements on mobile devices: What is the best approach for handling zoom?

I am facing a challenge with displaying interstitial ads on mobile sites. Different publishers may have varying viewport settings and initial scales on their mobile sites, making it difficult to ensure that the ad appears correctly on all devices with the ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

update certain parts of a webpage using ajax and still allow users to

Currently, I am implementing a partial update feature on the page using Ajax for a shopping cart. The cart updates in real-time as users add items to it. However, there is an issue when users navigate to the checkout page and then click the back button - t ...

Guide to assigning array elements to an object array with key value pairs

I am looking to enhance an object array with key value pairs by extracting information from a given array The resulting array must contain uniqueIds const characters = [ { name: "Luke Skywalker", height: "172", mass: "77", e ...

Adding event listeners to modal buttons in a Handlebars template is a simple process that involves utilizing the `

I've been working on developing a web application that interacts with a news API to display articles. Each article is presented in a card format, and I have also incorporated modals using handlebars. My goal is for each card's button to trigger ...

Challenge with setting asynchronous default value in React Material UI Autocomplete

Utilizing the 'Material UI' Autocomplete component to show a dropdown in my form. Whenever the user wishes to edit an item, the dropdown should autofill with the corresponding value fetched from the database. Attempting to simulate this scenario ...

"Utilizing the splice method to insert an element at specified indexes within an

const list = [] const obj = { name: '', mobile: '' } _.forEach(errors, (value, key) => { // eslint-disable-next-line no-debugger // debugger const field = key. ...

Need help figuring out how to use Javascript:void(0) to click a button in Selenium?

Struggling with finding the right solution, I have attempted various methods. Apologies for any formatting errors, but the element that requires clicking is: <button href="javascript:void(0)" id="payNewBeneficiary" class="button-new-payee"> ...

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

Tips on deactivating a button after it has been clicked once within a 24-hour period and reactivating it the following day with the use of JavaScript and Angular

Is it possible to disable my button after one click per day, and then automatically re-enable it the next day once a user has entered details using the submit button? I need assistance with JavaScript or AngularJS for this functionality. ...

Scroll indefinitely, obliterate and regenerate elements as you scroll

I have a unique issue that I need advice on from experts in this field. On my website, I have a Tree with infinite scroll functionality. The tree's image is iterative and the number of iterations depends on the data source provided. The data source ...

Check to see if the item is not already in the cart, and if so, add it and then increase its quantity

Utilizing React context, I have implemented a simple logic to add products to the cart using the useReducer hook for adding items. If we look at the Redux Toolkit implementation, here is my redux logic: const cartItemSlice = createSlice({ name: " ...

How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body. Succeeded in limiting movement on the top and left sides. Encountering difficulty restricting motion on the right side and bottom. e.pageX -= e.offsetX; e.pageY -= e.offsetY; ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Creating HTML code from a multidimensional array is a useful skill to

I am looking to use PHP to generate HTML code similar to the following: <li id="821">Accessories for tablets and cell phones <ul> <li id="426">Cell Phone Accessories <ul> <li id="675">Stands and Docks</ ...