Javascript(本地存储)仅存储一个值。我如何存储一切?

Gag*_*ago 2 javascript local-storage

我从开放的API获取用户数据,将其存储在本地存储中,可以显示所有数据,但是只有第一个值被保存在本地存储中。如何存储所有数据?

我的代码:

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

function createNode(element) {
  return document.createElement(element);
}

function append(parent, element ) {
  return parent.appendChild(element);
}

const ul = document.getElementById('authors');
const url = 'https://randomuser.me/api/?results=10';

fetch(url)
  .then((resp) => resp.json())
  .then(function(data) {

    let authors = data.results;

    return authors.map(function(author) {

      const myObj = {
        name: `${author.name.first}`,
        lastname : `${author.name.last}`,
        email : `${author.email}`,
        location : `${author.location.city}, ${author.location.street}`,
        phone : `${author.phone}`
      }

      let li = createNode('li'),
          img = createNode('img'),
          span = createNode('span');

      let myObj_serialized = JSON.stringify(myObj);

      localStorage.setItem("myObj" , myObj_serialized);

      let myObj_deserialized = JSON.parse(localStorage.getItem("myObj"));

      document.getElementById('authors').innerHTML += 
        myObj_deserialized.name.capitalize() +  " " + 
        myObj_deserialized.lastname.capitalize() + " --- " + 
        myObj_deserialized.email + " --- " + 
        myObj_deserialized.location.capitalize() + " --- " + 
        myObj_deserialized.phone + "<br/> " ;

      console.log(myObj);    
    })
  })

  .catch(function(error) {
     console.log(error);
   });
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明

在这里,我们看到只存储了1个值,而不是10个。

在此处输入图片说明

小智 5

每次在localstorage中都覆盖相同的对象,因此在maplocalstorage项的末尾myObj设置为authors数组中的最后一项。我建议使用唯一的东西,例如用户的email,并将其设置在localstorage中。

  localStorage.setItem(author.email , myObj_serialized);

  let myObj_deserialized = JSON.parse(localStorage.getItem(author.email));
Run Code Online (Sandbox Code Playgroud)