如何将新数组添加到本地存储中的当前数组元素?

时间:2018-07-18 09:56:19

标签: javascript jquery html5 css3

我在本地存储中创建了一个用户数组:

let btnSignUp = document.getElementById("btnSignUp");
btnSignUp.addEventListener('click', (e) => {
  let existingUsers = JSON.parse(localStorage.getItem("allUsers"));
  if (existingUsers == null) existingUsers = [];

  let userLogin = document.getElementById('authLogin').value;
  let userEmail = document.getElementById('authEmail').value;
  let userPassword = document.getElementById('authPassword').value;
  let userConfirmPassword = document.getElementById('authConfirmPassword').value;
  if (userPassword == userConfirmPassword) {
    let users = {
      "login": userLogin,
      "email": userEmail,
      "password": userPassword,
      "contacts": []
    };
    localStorage.setItem("users", JSON.stringify(users));
    // Save allEntries back to local storage
    existingUsers.push(users);
    localStorage.setItem("allUsers", JSON.stringify(existingUsers));
  } else {
    alert("Password and confirm password must be the same");
  }
}, false);

现在我需要为所选用户创建一个联系人数组。联系人应如下所示:

let userSurname = document.getElementById('_surname').value;
let userName = document.getElementById('_name').value;
let userCountry = document.getElementById('_country').value;
let userCity = document.getElementById('_city').value;
let userEmail = document.getElementById('_email').value;
let userPhone = document.getElementById('_phone').value;
let userWorkPlace = document.getElementById('_workPlace').value;

let contact = {
  "surname": userSurname,
  "name": userName,
  "country": userCountry,
  "city": userCity,
  "email": userEmail,
  "phone": userPhone,
  "workPlace": userWorkPlace
};
localStorage.setItem("contact", JSON.stringify(contact));

请告诉我该怎么做。

2 个答案:

答案 0 :(得分:0)

创建联系人对象数组。JSON.stringify该联系人对象数组

 let contacts = [];
 let contactObj = {
  "surname": userSurname,
  "name": userName,
  "country": userCountry,
  "city": userCity,
  "email": userEmail,
  "phone": userPhone,
  "workPlace": userWorkPlace
};
contacts.push(contactObj)
localStorage.setItem("contact", JSON.stringify(contacts));

答案 1 :(得分:0)

如果您担心反复需要对特定用户的联系人列表进行反序列化和序列化,则可以使用以下两个功能将联系人保留在本地存储中。这可能不是一个完美的解决方案。但这解决了您的担忧。根据您的要求,尝试为此构建自己的解决方案。

要保持联系

function addContact(username,contact){
    let count = localStorage.getItem(username+"-contacts-count") || 0;
    contact.index = count;
    localStorage.setItem(username+'-contact-'+(count++),JSON.stringify(contact));
    localStorage.setItem(username+"-contacts-count",count);
}

要检索联系人

function getContacts(username){
    let count = localStorage.getItem(username+"-contacts-count") || 0;
    let contacts = [];
    for(let i = 0;i<count;i++){
        let contact = localStorage.getItem(username+'-contact-'+(i));
        if(contact){
            contacts.push(JSON.parse(contact));
        }
    }
    return contacts;
}