我现在从后端获取了一个数组,数组里面有n个对象,对象里面又有n个数组,当然里面也有对象,可能描述有点混乱,下面有代码可以一目了然,我现在要做的是获取数组里的数组对象的所有个数,然后再获得对象里name为a的个数,我首先想到的是for循环和便利函数,这两种方法都能便利出每个数组里的对象个数,但是怎么全部加起来呢?然后我试了累加的方法实现不了,也可能是我的技术不行,后来我就问了一下公司的前端同事,短短 的几行代码就达到了我要的目的,实在是佩服,感觉后期肯定能用到,所以在这里整理出来,毕竟自己技不如人。。好了,上代码。
<template>
<div class="hello">name为a的个数:{
{medalStatus.nameLength}}总个数:{
{medalStatus.total}}
</div>
</template><script>
export default {name: "HelloWorld",data () { return { lists: '' }},methods: { getData () { var listArry = [ { typeList: [ { id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" } ], type: 1 }, { typeList: [ { id: 2, name: "b" }, { id: 3, name: "a" } ], type: 2 }, { typeList: [ { id: 3, name: "c" } ], type: 3 }, { typeList: [ { id: 4, name: "d" } ], type: 4 }, { typeList: [ { id: 5, name: "a" } ], type: 5 } ] this.lists = listArry }},computed: { medalStatus () { console.log(this.lists) let total = 0 let nameLength = 0 this.lists.forEach(dict => { let nameList = dict.typeList.filter(item => item.name === "a") nameLength = nameLength + nameList.length total = total + dict.typeList.length }) return { nameLength, total } }},created: function () { this.getData()}
}
</script>