繁体   English   中英

如何将字典从 localStorage 转换为 Vue 中的对象数组?

[英]How do I convert a dictionary from localStorage to an array of objects in Vue?

我正在尝试将字典从 localStorage 转换为对象数组。 我需要它来使用.filter() function,但是在转换它时出现 TypeError。

它表明this.savedNews是 Vue 控制台中的一个数组,但是使用Array.isArray()进行类型检查会返回false typeof()也产生不同的结果(见下文):

  data() {
    return {
      savedNews: Array // -> case 1
     //savedNews: []  ->  case2 
    }
  },
  mounted() {

    console.log(typeof(this.savedNews)) 
    // case1 -> returns 'function'
    // case 2 -> returns 'object'

    if(localStorage.savedNews){
      let storedSavedNews = JSON.parse(localStorage.getItem('savedNews'))
      this.savedNews = Object.keys(storedSavedNews).map((key) => {
          return storedSavedNews[key]
      })
    }
  },
  computed: {
    filteredSavedNews() {

        console.log(typeof(this.savedNews))
        // case 1 -> returns 'function', then 'object'
        // case 2-> 'object', 'object'

        return this.savedNews
    }
  },

如果你用savedNews: Array初始化,它就是 function; 因为它不是数组 Object 的实例,所以它是构造函数。

typeOf(Array)       // function  (It is constructor of Array)
typeOf(new Array()) // Object    (Instance of Array)
typeOf([])          // Object    (Instance of Array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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