【问题标题】:How to get single value from array in VueJs如何从VueJs中的数组中获取单个值
【发布时间】:2020-04-08 11:43:09
【问题描述】:

告诉初学者如何从数组中的所有对象中获取所有标题

这是我的数组

0: {id: 6, category_id: 2, title: "Test", brand: "Test", serial_number: "2165412315864",…}

1: {id: 7, category_id: 3, title: "Test2", brand: "Test2", serial_number: "2165412315864",…}

2: {id: 8, category_id: 5, title: "New", brand: "New", serial_number: "2165412315864",…}

3: {id: 9, category_id: 1, title: "New2", brand: "New2", serial_number: "2165412315864",…}

我尝试使用此代码

categories: {
            handler(categories) {
                console.log('categories: ', categories[title]); //Debug
            },
            deep: true
        }

【问题讨论】:

  • 那么到底是什么问题?

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

如果您想要一个仅包含标题的数组,您可以使用 Array.map 并选择您感兴趣的部分:

const arr = [{
    id: 6,
    category_id: 2,
    title: "Test",
    brand: "Test",
    serial_number: "2165412315864"
  },
  {
    id: 7,
    category_id: 3,
    title: "Test2",
    brand: "Test2",
    serial_number: "2165412315864"
  },
  {
    id: 8,
    category_id: 5,
    title: "New",
    brand: "New",
    serial_number: "2165412315864"
  },
  {
    id: 9,
    category_id: 1,
    title: "New2",
    brand: "New2",
    serial_number: "2165412315864"
  }
];

const titles = arr.map(({ title }) => title);

console.log(titles);

【讨论】:

    【解决方案2】:

    这里categories变量其实是一个数组,所以不能用

    categories['title']
    // Or,
    categories.title
    

    这里。要获取categories 数组中每个类别的所有title 属性,您可以使用数组.map() 方法,例如:

    categories: {
      handler(categories) {
        const arr = categories.map(c => c.title)
        console.log('titles: ', arr); //Debug
      },
      deep: true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2014-04-21
      • 2017-07-29
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      相关资源
      最近更新 更多