如何在vuejs中获取属性的长度

shyt4zoc  于 2023-05-18  发布在  Vue.js
关注(0)|答案(2)|浏览(183)

我有这个json

{
   [{
    "status": "delivered"
  }, {

    "status": "delivered"
  }, {

    "status": "cancelled"
  }, {
    "status": "on Delivery"
  }]
}

我试图得到“status”的总长度:“delivered”在json中我们有两个“delivered”,那么我怎么得到“delivered”的长度,也就是2,我怎么做剩下的状态
这是我的vue组件

<script>
import axios from "axios";
export default {
  data() {
    return {
      orders: null,
    };
  },
  created() {
 axios.get("http://localhost:5000/api/orders").then((response) => {
      this.orders = response.data;
    });
  },

};
</script>
cngwdvgl

cngwdvgl1#

你可以过滤数组并获取长度:

const obj = { "orders": [{ "status": "delivered" }, { "status": "delivered" }, { "status": "cancelled" }, { "status": "on Delivery" }]}
const res = obj.orders.filter(o => o.status === 'delivered').length
console.log(res)
thigvfpy

thigvfpy2#

首先,您提供一个未格式化的JSON。我想你的意思是处理这个数组:

const orderArray = [
      { "status": "delivered" }, 
      { "status": "delivered" }, 
      { "status": "cancelled" }, 
      { "status": "on Delivery" }
    ]

const lengthOfDelivered = 
orderArray.filter((order)=>order.status=='delivered').length

此外,如果您想将其他状态计入表中:

let countTable = []
orderArray.forEach(order => {
    const idx = countTable.findIndex(item => item.status === order.status)
    if (idx !== -1) {
        countTable[idx]['count'] += 1
    } else {
        countTable.push({...order, count: 1})
    }
})
console.log(countTable);

相关问题