【问题标题】:How to retrieve value of key from an object inside an array如何从数组内的对象中检索键的值
【发布时间】:2020-05-05 03:08:51
【问题描述】:

我正在尝试从以下数组中检索商家名称:

[
  {
    "model": "inventory.merchant",
    "pk": 1, 
    "fields": {
      "merchant_name": "Gadgets R Us",
      "joined": "2020-01-06T07:16:17.365Z"
    }
  },
  {"model": "inventory.merchant", "pk": 2, "fields": {"merchant_name": "H&M", "joined": "2020-01-07T22:21:52Z"}},
  {"model": "inventory.merchant", "pk": 3, "fields": {"merchant_name": "Next", "joined": "2020-01-07T22:22:56Z"}},
  {"model": "inventory.merchant", "pk": 4, "fields": {"merchant_name": "Jill Fashion", "joined": "2020-01-07T22:26:48Z"}}
]

我正在使用 vuejs,并使用 axios 通过 api 获取上述数据。我放入了一个名为merchants[] 的数组。我可以使用 v-for 从我的 html 中获取我想要的任何项目,即

<div v-for="merchant in merchants">
  <p>{{ merchant.fields.merchant_name }}</p>
</div>

但是,在我的 .js 文件中,执行以下操作不起作用:

console.log(this.merchants[0].fields.merchant_name)

我在控制台中收到以下错误:

vue.js:634 [Vue warn]: Error in render: "TypeError: Cannot read property 'fields' of undefined"

请帮忙

编辑: 这是我的 .js 文件。我尝试通过merchantName() 计算属性在控制台中记录商家名称:

new Vue({
  delimiters: ['[[', ']]'],
  el: "#inventory",

  data: {
    gallery: true,
    inCart: false,
    shipping: false,
    galleryView: "zoom",
    ref: "",
    cart: [],
    isSelected: false,
    selectedClass: "in_cart",
    shippingCost: 2000,
    inventory: [],
    merchants: [],
  },
  methods: {
    zoomGallery(){
      this.galleryView = "zoom"
    },
    back(){
      this.gallery = "thumbnail"
    },
    addToCart(name, merchant, price, qty, image, id){
      var itemClone = {}
      itemClone = {
        "merchant": merchant,
        "name": name,
        "price": price,
        "qty": qty,
        "image": "/media/" + image,
        "id": id,
      }
      this.cart.push(itemClone)
      this.isSelected = true
    },
    removeFromCart(index){
      this.cart.splice(index, 1)
    },
    deleteFromCart(id){
      console.log(id)
      // right now, any caret down button deletes any input
      // I need to use components to prevent that
      if (this.cart.length > 0){
        index = this.cart.findIndex(x => x.id === id)
        this.cart.splice(index, 1)
      }
    },
    viewCart(){
      this.gallery = false
      this.shipping = false
      this.inCart = true
    },
    viewShipping(){
      this.gallery = false
      this.shipping = true
      this.inCart = false
    }
  },
  computed: {
    itemsInCart(){
      return this.cart.length
    },
    subTotal(){
      subTotal = 0
      inCart = this.cart.length
      for (i=0; i<inCart; i++) {
        subTotal += Number(this.cart[i].price)
      }
      return subTotal
    },
    checkoutTotal(){
      return this.subTotal + this.shippingCost
    },
    merchantName(){
      console.log(this.merchants[0])
    },
  },
  beforeMount() {
    axios
      .get("http://127.0.0.1:8000/get_products/").then(response => {
        (this.inventory = response.data)
        return axios.get("http://127.0.0.1:8000/get_merchants/")
      })
      .then(response => {
        (this.merchants = response.data)
      })
  },
});

编辑: 来自 console.log(this.merchants) 的响应是:

[__ob__: Observer]
length: 0
__ob__: Observer
value: Array(0)
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array
dep: Dep
id: 16
subs: Array(0)
length: 0
__proto__: Array(0)
__proto__: Object
vmCount: 0
__proto__:
walk: ƒ walk(obj)
observeArray: ƒ observeArray(items)
constructor: ƒ Observer(value)
__proto__: Object
__proto__: Array

【问题讨论】:

  • 商家初始值是多少
  • 你在哪里登录console.log(this.merchants[0].fields.merchant_name)?
  • &lt;p v-if="merchant"&gt;{{ merchant.fields.merchant_name }}&lt;/p&gt;
  • 您好@PranavCBalan,商家中什么都没有。我将其初始化为商家 [] @FatemeFazli 我只是使用一个组件将其发布到控制台只是为了查看输出,即`merchantName(){ console.log(this.merchant[0].fields.merchant_name) } `
  • 我认为您应该分享控制台记录 this.merchants[0].fields.merchant_name 的方式和位置

标签: arrays vue.js javascript-objects


【解决方案1】:

为什么你试图在计算属性中 console.log this.merchants。检查 vuejs here 的计算属性。

在来自 API 调用的数据到来之前,您的数据是空的。这就是为什么你的this.merchants 是空的。

您可以通过使用方法获取 this.merchants 值,并在您的 api 调用后运行它或像这样观看:

watch: {
  merchants: function () {
    console.log(this.merchants)
  }
}

每当this.merchants数组发生变化时,它都会控制台。

【讨论】:

  • 谢谢,但这告诉我我做错了什么,但不是正确的方法。你知道我怎样才能使数组不为空。
  • 你想让你的 this.merchants 在 computed 中不为空吗?我认为您可以在这种情况下使用watch。我正在更新我的答案以说明如何。
猜你喜欢
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 2022-01-06
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2019-11-03
相关资源
最近更新 更多