简体   繁体   中英

How to add a new object with all properties in an existing array

Can somebody help me in creating a new object with all the properties and insert in the phonebook array?

var phonebook = [
  {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "000/111-111",
    address: ['street', '1', 'city', '00000']
  },
  {
    firstName: "John1",
    lastName: "Doe1",
    phoneNumber: "000/111-111",
    address: ['street', '2', 'city', '00000']
  },

     //add new one here;
  ];

phonebook.addNewContact = function(fname, lname, phonenum, address){
    this.firstName = fname; 
    this.lastName =  lname;
    this.phoneNumber = phonenum;
    this.address= address;
}

You could do it like this, basically just calling the method you created, but I suggest you use a constructor:

var phonebook = [
  {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "000/111-111",
    address: ['street', '1', 'city', '00000']
  },
  {
    firstName: "John1",
    lastName: "Doe1",
    phoneNumber: "000/111-111",
    address: ['street', '2', 'city', '00000']
  },

     //add new one here;
  ];

phonebook.addNewContact = function(fname, lname, phonenum, address){
    this.firstName = fname; 
    this.lastName =  lname;
    this.phoneNumber = phonenum;
    this.address= address;
}


var newperson = new phonebook.addNewContact('john', 'doe', '000/111-111', ['street', '3', 'city', '00000']);

You can achieve this by using the push function:

For example:

var phonebook = [
  {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "000/111-111",
    address: ['street', '1', 'city', '00000']
  },
  {
    firstName: "John1",
    lastName: "Doe1",
    phoneNumber: "000/111-111",
    address: ['street', '2', 'city', '00000']
  }
];

function addNew(fname, lname, phonenum, address){
    phonebook.push({
        firstName: fname,
        lastName: lname,
        phoneNumber: phonenum,
        address: address
    });
}

It looks like you're trying to add to the phonebook array, if this is what you intend then you'd go about it like so:

 var phonebook = [ { firstName: "John", lastName: "Doe", phoneNumber: "000/111-111", address: ['street', '1', 'city', '00000'] }, { firstName: "John1", lastName: "Doe1", phoneNumber: "000/111-111", address: ['street', '2', 'city', '00000'] } ]; var addNewContact = function(fname, lname, phonenum, address){ phonebook.push({ firstName: fname, lastName: lname, phoneNumber: phonenum, address: address }); }; addNewContact('Jamie', 'Bonnett', '000/111-111', ['street', '0', 'city', '00000']); document.write('<pre>' + JSON.stringify(phonebook) + '</pre>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM