Javascript(本地存储)仅存储一个值。如何存储所有内容?

时间:2019-03-27 12:20:21

标签: 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);
   });

结果:

enter image description here

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

enter image description here

4 个答案:

答案 0 :(得分:5)

您每次都在localstorage中覆盖同一对象,因此在map的末尾,localstorage项目myObj设置为authors数组中的最后一项。我建议使用诸如用户的email之类的独特内容,并将其设置在本地存储中。

  localStorage.setItem(author.email , myObj_serialized);

  let myObj_deserialized = JSON.parse(localStorage.getItem(author.email));

答案 1 :(得分:4)

在将数据存储在WITH scored_rows AS ( SELECT *, SUM(CASE WHEN status = 'remove' THEN -1 ELSE 1 END) OVER (ORDER BY timestamp DESC, id DESC) AS score FROM tblAuthors ), checked_scored_rows AS ( SELECT *, MAX(score) OVER (ORDER BY timestamp DESC, id DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING ) AS previous_max_score FROM scored_rows ) DELETE tblAuthors FROM checked_scored_rows WHERE checked_scored_rows.id = tblAuthors.id AND checked_scored_rows.score <= COALESCE(checked_scored_rows.previous_max_score, 0) 函数内部时,每次循环迭代都将覆盖对象键map

您会注意到myObj中只有最后一个对象。

您应该存储整个响应有效负载

LocalStorage

答案 2 :(得分:1)

本地存储是一个地图。 因此,通过调用setItem(key, value)可以覆盖该值。 您可以使用多个键,也可以创建一个数组并保存整个数组。

答案 3 :(得分:1)

**基本概念map()方法:**

  1. map()创建一个具有调用函数结果的新数组 每个数组元素。
  2. 此方法为数组中的每个元素依次调用提供的函数。
  3. 没有值的数组元素不执行。
  4. 原始数组不变。

return authors.map(function(author,index, arr) {

      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(index , myObj_serialized);

          let myObj_deserialized = JSON.parse(localStorage.getItem(index));

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

     

    })

OR

let myObj_serialized = JSON.stringify(myObj);

          localStorage.setItem(myObj.phone , myObj_serialized);

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

OR

  let myObj_serialized = JSON.stringify(myObj);

          localStorage.setItem(myObj.email , myObj_serialized);

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